求二叉树的深度和宽度[Java]
来源:互联网 发布:好看的淘宝头像图片 编辑:程序博客网 时间:2024/06/05 08:10
1.二叉树深度
这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。
private static int getHeight(BiNode head) { if(head==null) //结束条件 return 0;/* else if(head.left==null||head.right==null) return 1;*/ //这一句可要可不要 else return 1+Math.max(getHeight(head.left), getHeight(head.right));}
2.二叉树宽度
使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。
private static int getWidth(BiNode head) {if(head==null)return 0;int max=1; LinkedList<BiNode>ll=new LinkedList<BiNode>();ll.add(head);while(true){int len=ll.size();if(len==0)break;while(len>0){BiNode b=ll.poll();len--;if(b.left!=null)ll.add(b.left);if(b.right!=null)ll.add(b.right);}max=Math.max(max, ll.size());}return max;}
0 0
- 求二叉树的深度和宽度[Java]
- 求二叉树的深度和宽度[Java]
- 求二叉树的深度和宽度[Java]
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉树的深度和宽度
- 求二叉数的深度和宽度
- 求二叉数的深度和宽度
- 求二叉树宽度和深度
- 华为练习 求二叉树的宽度和深度
- 求二叉树的深度和宽度平衡最大距离
- 求二叉树的深度、宽度和叶子结点数
- 华为oj 求二叉树的深度和宽度
- 回车登录(支持IE 和 火狐等浏览器)
- android4.0触摸屏(touchscreen)以及屏幕按键驱动解析
- CSDN博客积分规则
- EazyUI布局问题
- ubuntu启动过程
- 求二叉树的深度和宽度[Java]
- Windows环境下Android Studio v1.0安装教程
- Java学习笔记八(反射)
- “The connection to adb is down, and a severe error has occured”的解决方法汇总
- QString & String
- 无刷新上传
- ssh 免密码登录配置
- Cocos-js——粒子系统
- 基于FT5x06嵌入式Linux电容触摸屏驱动