二叉树的建立及其前中后序遍历

 1 //二叉树存储结构:
 2 struct node
 3 {
 4     Int data;
 5     node *lchild;
 6     node *rchild;
 7 };
 8 
 9 //二叉树在建树前根节点不存在:
10 Node *root = NULL;
11 
12 //新建结点:
13 node *newNode(int v)
14 {
15     node *Node = new node;
16     Node->data = v;
17     Node->lchild = NULL;
18     Node->rchild = NULL;
19     return Node;
20 }
21 
22 //二叉树结点的查找、修改:
23 void search(node *root,int x,int newdata) // 在这里修改的是root指针指向的内容,所以不需要加引用&
24 {
25     if(root == NULL)
26         return;
27     if(root->data == x)
28         root->data = newdata;
29     search(root->lchild,x,newdata);
30     search(root->rchild,x,newdata);
31 }
32 
33 //二叉树的插入:
34 void insert(node *&root,int x) // 这里要加引用,是因为修改的是root指针本身 
35 {
36     if(root == NULL)
37     {
38         root = newNode(x);
39         return root;
40     }
41     if(x<=root->data)   // 生成二叉查找树 
42         insert(root->lchild,x);
43     else
44         insert(root->rchild,x);
45 }
46 
47 //二叉树的创建:
48 node *create(int data[],int n)   
49 {
50     node *root = NULL;
51     for(int i=0;i<n;++i)
52         insert(root,data[i]);
53     return root;    
54 }

二叉树的遍历:
遍历方法一般有四种,先序遍历、中序遍历、后序遍历、层次遍历,前三种的前中后指的是根结点root在遍历中的位置。

 1 void preorder(node *root) // 对于先序遍历,序列第一个一定是根结点 
 2 {
 3     if(root==NULL)
 4         return;
 5     cout << root->data;
 6     preorder(root->lchild);
 7     preorder(root->rchild);
 8 }
 9 
10 void inorder(node *root) //中序遍历总把根结点放在左子树和右子树中间 
11 {
12     if(root==NULL)
13         return;    
14     inorder(root->lchild);
15     cout << root->data;
16     inorder(root->rchild);
17 } 
18 
19 void postorder(node *root) //后序遍历中的序列最后一个一定是根结点 
20 {
21     if(root==NULL)
22         return;
23     postorder(root->lchild);
24     postorder(root->rchild);
25     cout << root->data;
26 }
27 
28 void LayerOrder(node *root) //根据题意,原存储结构可能要加入layer记录层数 
29 {
30     queue<node*> q; // 队列中的数据类型是指针,这样可以方便有时层序遍历的时候修改数据    
31     q.push(root);
32     while(!q.empty())
33     {
34         node *now = q.front();
35         q.pop();
36         if(now->lchild!=NULL)
37             q.push(now->lchild);
38         if(now->rchild!=NULL)
39             q.push(now->rchild);
40     }
41 }

推论:中序序列可以与先序序列、后序序列、层序序列中的任意一个来构建唯一的二叉树
例如:先序序列和中序序列搭配:

 1 node *create(int preL,int preR,int inL,int inR) // preL,preR是先序序列的区间 
 2 {
 3     if(preL>preR) //先序序列长度小于等于0时,直接返回 
 4         return NULL;
 5     node *root = new node;
 6     root->data = pre[preL];
 7     int k;
 8     for(k=inL;i<=inR;++i) { if(in[k]==pre[preL]) break; } int num = k-inL; // num是左子树结点个数 root->lchild = create(preL+1,preL+num,inL,k-1);
 9     root->rchild = create(preL+num,preL+num+1,k+1,InR);
10     return root;
11 }

猜你喜欢

转载自www.cnblogs.com/kachunyippp/p/10256793.html