题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路
我已看到这个题目的时候,就想到了利用分冶的方法,利用递归的思路。我们只要找到出口,分了之后就要合并啊。和我们的归并排序有点意思哦,昨天晚上做的那个类似的思路。
当前结点的Length=max(left,right)+1;
这个就是我的解题思路!
其实还有思路。比如哈。我们层次遍历,也可以以解决这个问题。
代码:递归的
package JianzhiOffer;
/**
* 分冶思路
* @author JetWang
*
*/
public class Slution36 {
public int TreeDepth(TreeNode root) {
return finLength(root);
}
public int finLength(TreeNode root){
if(root==null){
return 0;
}
int leftLegnth=finLength(root.left);
int rightLength=finLength(root.right);
if(leftLegnth>=rightLength){
return leftLegnth+1;
}
return rightLength+1;
}
}
对于第二种处理思路
我们如何计算高度呢
1
2 3
4 5 6 7
8 9 10 11 12 13 14
这个是我们自己创造的标准的二叉树,如果层次遍历,我们怎么遍历呢?
1 |
2 3 |
4 5 6 7|
8 9 10 11 12 13 14 |
我们每次都必须把他们的孩子全部遍历掉。比如我现在处理 1结点。那么我必须把他的左右孩子结点加入到我们的队列中,此时层数加一。
现在我们的队列中有 2 3这两个节点,同理我们也必须把 2 3结点的所有的孩子加入进入。差不都的意思就是,要把上一次加入的全部遍历掉。这个就是效果~~
public int TreeDepth2(TreeNode root){
if(root==null){
return 0;
}
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(root);
int count=0;
while(queue.isEmpty()==true){
//1(1) | 2 3 (2)| 3 4 5 6 (3)|......这个就是我们计算高度的方式
count++;
int length=queue.size();
//把当前层的孩子全部处理完毕,那么队列还有孩子,层数毕竟一定会加一
while(length>=1){
TreeNode node=queue.poll();
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
}
return count;
}