首页 > 其他 > 详细

二叉树的递归操作

时间:2014-02-25 14:08:19      阅读:274      评论:0      收藏:0      [点我收藏+]

1,二叉树的遍历

二叉树的遍历操作分为常见的前序遍历(Preorder transversal),中序遍历(Inorder transversal)以及后序遍历(Postorder transversal)。

前序遍历:根----->左子树----->右子树

bubuko.com,布布扣
1 void preorder_transversal(BinTree& root){
2     if(root){
3         cout<<root->data<<" ";
4         preorder_transversal(root->left);
5         preorder_transversal(root->right);
6     }
7 }
View Code

中序遍历:左子树------>---->右子树

bubuko.com,布布扣
1 void inorder_transversal(BinTree& root){
2     if(root){
3         inorder_transversal(root->left);
4         cout<<root->data<<" ";
5         inorder_transversal(root->right);
6     }
7 }
View Code

后序遍历:左子树---->右子树------>

bubuko.com,布布扣
1 void postorder_transversal(BinTree& root){
2     if(root){
3         postorder_transversal(root->left);
4         postorder_transversal(root->right);
5         cout<<root->data<<" ";
6     }
7 }
View Code

2,二叉树的层高

层高就是取左子树和右子树的层高的最大值加一(加上根所在的层): max( height( root->left ), height( root->right ) ) +1

bubuko.com,布布扣
1 int height(BinTree root){
2     if(root==NULL)
3         return 0;
4     else
5         return height(root->left) > height(root->right)? height(root->left)+1:height(root->right)+1;
6 }
View Code

3,二叉树的层次遍历

用递归按层遍历二叉树不好理解。

1,该函数应该有两个参数:二叉树的根节点以及要遍历的层数

2,遍历第0层,应该直接访问根节点的数据;

3,遍历第N层,相对于遍历root的左子树和右子树的第N-1层。 

 

bubuko.com,布布扣
 1 void printNodeAtLevel1(BinTree root, int level){
 2     if(!root || level < 0)
 3         return ;
 4     else if(level == 0)
 5     {
 6         cout << root->data <<" ";
 7     }
 8     else{
 9         printNodeAtLevel1(root->left, level - 1);
10                printNodeAtLevel1(root->right, level - 1);
11     }
12 }
View Code

二叉树的递归操作

原文:http://www.cnblogs.com/nigang/p/3564974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!