Book--二叉树

2014-07-05 11:13:35

小白二叉树专题结束了,来做个小结吧(时间有点晚了)

1:首先来说说二叉树的基础:node结构体,即将每个节点看做是一个node结构体单元

1 struct node{
2     int val;
3     node *left,*right;
4     node(){
5         val = 0;
6         left = right = NULL;
7     }
8 };

 

 2:再来谈谈如何建树。

  首先比较典型的根据(1)InOrder(2)-1为叶子节点标志  这两个条件来建树:

 1  node *Build_tree(){
 2      node *next = new node;
 3      cin >> num;
 4      if(num == -1)
 5          return NULL;
 6      next->val = num;
 7      next->left = Build_tree();
 8      next->right = Build_tree();
 9      
10     return next;
11 }

 

  其次有根据(1)InOrder (2)PostOrder  这两个条件来建树

 1  //首先要说明的是这里main函数里对post读入进行了倒序读入处理,所以post[0]是root节点
 2  node * Build_tree(int *in,int *post,int cnt){
 3      if(cnt <= 0)
 4          return NULL;
 5      node *next = new node;
 6      int pos;
 7      for(pos = 0; pos < cnt ; ++pos)
 8          if(in[pos] == post[0])
 9              break;
10      if(pos > 0)
11         next->left = Build_tree(in,post + cnt - pos,pos);
12      if(pos < cnt - 1)
13          next->right = Build_tree(in + pos + 1,post + 1,cnt - pos - 1);
14      next->val = post[0];
15 
16      return next;
17 }

 

PS:6行开始的循环是为了找当前所需要找的postnode在InOrder中的位置index,则从0到index - 1为左子树,index + 1到cnt - 1为右子树,这里的核心是以post + k的形式传位置,并以cnt代表长度。所以就有了:左子树存在时(pos > 0),post+cnt-pos是左子树根结点在post中的位置,pos是左子树长度;右子树存在时(pos < cnt - 1),post+1是右子树根节点在post中的位置,cnt-pos-1是右子树的长度(长度指元素个数)

3:如何遍历一颗二叉树,显然采用DFS是比较便利的。

1 void Dfs(node *tem,int sum){
2     if(tem == NULL)
3         return;
4     if(tem->left == NULL && tem->right == NULL){
5         //.....条件   
6     }
7     Dfs(tem->left,sum + tem->val);
8     Dfs(tem->right,sum + tem->val);
9 }

 

4:为了防止内存泄露,delete函数当然是要写的啦。

 1  void Delete(node *tem){
 2      if(!tem)
 3          return;
 4      if(tem->left != NULL)
 5          Delete(tem->left);
 6      if(tem->right != NULL)
 7          Delete(tem->right);
 8      delete tem;
 9      tem = NULL; //Important
10  }
11  //一个比较标准的delete函数

 

 

posted @ 2014-07-05 14:34  Naturain  阅读(166)  评论(0)    收藏  举报