牛客:实现二叉树先序,中序和后序遍历

https://www.nowcoder.com/practice/566f7f9d68c24691aa5abd8abefa798c?tpId=101&&tqId=33229&rp=3&ru=/activity/oj&qru=/ta/programmer-code-interview-guide/question-ranking

题目描述:输入一棵二叉树树,输入树的形式是每一行输入三个数,分别是节点value和左右孩子value。输出为树的先序、中序和后序遍历。

思路:首先根据输入的二叉树建树,然后进行先序、中序、后序遍历。

#include
#include
#include
#include
#include
using namespace std;
#define MAX_N 1000000
struct BinTree{
    int data;
    BinTree *lchild, *rchild;
} *root;
int n, N;
BinTree *CreateTree(int fa_index[][2], int value){
    if(value==0) return NULL;
    BinTree *p;
    p = (BinTree *)malloc(sizeof(BinTree));
    p->data = value;
    p->lchild = CreateTree(fa_index, fa_index[value][0]);
    p->rchild = CreateTree(fa_index, fa_index[value][1]);
    return p;
}
// 先序遍历
void PreOrder(BinTree *head){
    if(head){
        N += 1;
        if(N == n)
            printf("%d\n", head->data);
        else if(N < n)
            printf("%d ", head->data);
        PreOrder(head->lchild);
        PreOrder(head->rchild);
    }
}
//中序遍历
void InOrder(BinTree *head){ 
    if(head){
        InOrder(head->lchild);
        N += 1;
        if(N == n)
            printf("%d\n", head->data);
        else if(N < n)
            printf("%d ", head->data);
        InOrder(head->rchild);
    }
}
//后序遍历
void PostOrder(BinTree *head){ 
    if(head){
        PostOrder(head->lchild);
        PostOrder(head->rchild);
        if(head->data==root->data)
            printf("%d\n", head->data);
        else
            printf("%d ", head->data); 
    }
}
int main()
{
    int fa_index[MAX_N+1][2], value; //前提是节点的value不重复
    while(scanf("%d %d", &n, &value)!=EOF){
        memset(fa_index, 0, sizeof(fa_index));
        for(int i=0; i

 

你可能感兴趣的:(牛客,#,--二叉树)