剑指offer算法题
二叉树 深度
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
题目分析
方法一 递归
下面是JAVA算法实现:
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(left,right)+1;
}
方法二 循环
这种方法不会有递归方法容易出现的栈溢出风险。循环其实是广度优先的思想(BFS)。时间复杂度O(N)。
主要思想是先知道下一层树的个数,然后count++,相等时候,结束一层的层序遍历。
下面是JAVA算法实现:
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
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;
}