打印二叉树的深度
来源:互联网 发布:下载动画的软件 编辑:程序博客网 时间:2024/05/22 03:18
这道题本质上还是考查二元树的遍历
如果一棵树只有一个结点,它的深度为1。如果根结点只有左子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样如果根结点只有右子树而没有左子树,那么树的深度应该是其右子树的深度加1。如果既有右子树又有左子树呢?那该树的深度就是其左、右子树深度的较大值再加1。
上面的这个思路用递归的方法很容易实现,只需要对遍历的代码稍作修改即可
参考资料:剑指offer代码:
#include <iostream>using namespace std;typedef struct node{int data;struct node *lchild;struct node *rchild;}Node ,*pNode;void createTree(pNode & root){int temp;scanf("%d",&temp);if(0 != temp){root=(pNode) malloc (sizeof(Node));root->data = temp;createTree(root->lchild);createTree(root->rchild);}else{root=NULL;}}void print(const pNode root){ pNode p = root;if(p){cout<< p->data<< " ";print(p->lchild);print(p->rchild);}}//类似先序遍历,节点会重复访问,效率较低int btDepth(const pNode root){if(NULL == root)return 0;int left = btDepth(root->lchild);int right = btDepth(root->rchild);return left > right ? left + 1 : right + 1;}//类似后序遍历,效率比较高,不会重复访问节点void btDepth(const pNode root,int &depth){if(NULL == root){depth=0;return ;}int left ;btDepth(root->lchild,left); int right ;btDepth(root->rchild,right);depth = left > right ? left +1 : right +1;}int main(){pNode root=NULL;createTree(root);print(root);cout<<endl;cout<<btDepth(root);int depth=0;btDepth(root,depth);cout<<endl<<depth;return 0;}
二叉树测试:
运行结果:
0 0
- 打印二叉树的深度
- Java 按深度打印二叉树
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- hdu 1267 下沙的沙子有几粒?(递推&DP)
- FZU_ Problem 2148 Moon Game
- python字典
- 编程常用知识点大全(链接)
- COM(三)进程透明性、标准列集、自定义列集
- 打印二叉树的深度
- C语言 BMP图片处理
- 如何把pdf转换成excel转换器免费使用
- Codeforces Round #259 (Div. 2)-C. Little Pony and Expected Maximum
- CoreData学习记录
- struct list_head 解析
- 大数乘法(错于2*LEN-1)
- 黑马程序员-IO流中的字符流
- C 语言04