首页 > 其他 > 详细

二叉树的层序遍历(先序遍历建树)

时间:2020-04-23 21:46:25      阅读:79      评论:0      收藏:0      [点我收藏+]

我在建树的时候一开始用的循环,可能是没有理解递归的含义。

改过来之后就好了。

#include <iostream>

using namespace std;

typedef struct node
{
    int data;
    struct node *l,*r;
} BT;

BT *creat()
{
    BT *root;
    int temp;
    cin>>temp;// 
   // 原来我这里写的是,while(cin>>temp); {
if(temp == -1) { root = NULL; } else { root = new BT; root->data = temp; root->l = creat(); root->r = creat(); } } return root; } void travel(BT *root) { if(root) { BT *temp[100] = {NULL}; int in = 0,out = 0; temp[in++] = root; while(out < in)// 要不要加等号 { if(temp[out]->l != NULL)temp[in++] = temp[out]->l; if(temp[out]->r != NULL)temp[in++] = temp[out]->r; cout<<temp[out]->data<<endl; out++; } } else return; } int main() { BT *root = creat(); travel(root); return 0; }

 

二叉树的层序遍历(先序遍历建树)

原文:https://www.cnblogs.com/zhang-zsq/p/12740678.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!