C 二叉树的 三种遍历

// C二叉树的前中后遍历.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <stdio.h>
using namespace std;
struct node {
    int id;
    struct node* lchild;
    struct node* rchild;    
};
typedef struct node* BTREE;

struct node* newNode(int data) {
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->id = data;
    node->lchild = NULL;
    node->rchild = NULL;
    return node;
}

BTREE search_tree(BTREE t, int x) {
    if (!t)
        return NULL;
    if (t->id == x)
        return t;
    else
    {
        if (!search_tree(t->lchild, x))
            return search_tree(t->rchild, x);
    }
   // return t;
}

BTREE CreateBitree(BTREE root,int id,int l,int r) {    
    BTREE p = NULL;


    if (id == 0) {
        BTREE q = NULL;
        q = (BTREE)malloc(sizeof(BTREE));
        q->id = id;
        root = q;
    }
    p = search_tree(root, id);
    cout << p->id<<endl;
    

        if (l!=-1)
        {         
            
            node*  nl=newNode(l);            
            p->lchild = nl;
        }

        if(r!=-1)            
        {
            node* nr = newNode(r);            
            p->rchild = nr;
        }        
    return (root);
}


void printPostorder(struct node* node) {
    if (node == NULL)
        return;
    printPostorder(node->lchild);
    printPostorder(node->rchild);
    cout<<("%d ", node->id)<<" ";
}

void printInorder(struct node* node){
    if(node==NULL){
        return;
    }
    printInorder(node->lchild);
    printf("%d ",node->id);
    printInorder(node->rchild);
}
void printPreorder(struct node* node){
    if(node==NULL){
        return;
    }
    printf("%d ",node->id);
    printPreorder(node->lchild);
    printPreorder(node->rchild);
}



int main()
{
    int i,n;
    int id, l, r;
    BTREE root=NULL;
    node *p=NULL;
    cin>>n;
    for (i = 0; i < n; i++)
    {
        //scanf("%d %d %d", &id,&l,&r);
        cin >> id >> l >> r;
        root = CreateBitree(root,id,l,r);       
        
    }
    printPostorder(root);
    cout << endl;
	printInorder(root);
	cout << endl;
	printPreorder(root);
	cout << endl;

    cout << "\nHello World!\n";
	return 1;
}

猜你喜欢

转载自blog.csdn.net/laocooon/article/details/121768819