Java实现二叉树的深度
来源:互联网 发布:tough cookie.js 编辑:程序博客网 时间:2024/06/11 01:05
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度
我的第一版代码:想着用递归,哎....WRONG!
/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { public int TreeDepth(TreeNode root) { int re=1; int i=1,j=1; boolean flag=true; while(flag){ if(root.left!=null){ i++; root=root.left; }else if(root.right!=null){ j++; root=root.right; }else{ flag=false; } re=i>=j?i:j; } return re; }}
看了一下大神的代码:
链接:https://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b来源:牛客网import java.lang.Math;public class Solution { public int TreeDepth(TreeNode pRoot) { if(pRoot == null){ return 0; } int left = TreeDepth(pRoot.left); int right = TreeDepth(pRoot.right); return Math.max(left, right) + 1; }}
然后用非递归的方法做,也可以
链接:https://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b来源:牛客网public class Solution { public int TreeDepth(TreeNode pRoot) { if(pRoot == null){ return 0; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(pRoot); int depth = 0, count = 0, nextCount = 1; while(queue.size()!=0){ TreeNode top = queue.poll(); count++; if(top.left != null){ queue.add(top.left); } if(top.right != null){ queue.add(top.right); } if(count == nextCount){ nextCount = queue.size(); count = 0; depth++; } } return depth; }}
说是非常巧妙了:
阅读全文
0 0
- 二叉树的深度(Java实现)
- Java实现二叉树的深度
- 二叉树的深度java实现
- 二叉树的深度 Java
- 二叉树的深度 Java
- 二叉树的深度 java
- 求一颗二叉查找树的深度(java实现)
- 剑指offer----二叉树的深度----java实现
- java实现 二叉树的深度&判断二叉树是否是平衡二叉树
- java二叉树实现、遍历、求深度
- 数据结构与算法分析笔记与总结(java实现)--二叉树11:二叉树的深度
- 二叉树求深度的实现
- 求二叉树的深度代码实现
- Python实现二叉树的深度
- 二叉树的最大深度和最小深度实现
- java 求二叉树的深度
- Java代码 求二叉树的深度
- 求二叉树的深度 java描述
- jvm启动是单线程还是多线程?
- java用base64解密时,部分中文乱码原因
- ubuntu install phantomjs
- 六一儿童节PHP宝宝又被围剿了,迅速围观!
- java线程启动
- Java实现二叉树的深度
- 获取canvas中鼠标的坐标
- Mooc 面向对象程序设计 week2作业
- Java实现几种常见排序方法
- HDU-4571-spfa,记忆化搜索,背包,DP
- Python爬虫神器PyQuery的使用方法
- Node入门
- kotlin的必修之路
- 20170601