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

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

改过来之后就好了。

#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; }

猜你喜欢

转载自www.cnblogs.com/zhang-zsq/p/12740678.html