剑指offer
38 二叉树的深度
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
输入
{1,2,3,4,5,#,6,#,#,7}
输出
4
解法1:递归
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null)return 0;
//递归
int depleft = 1;
int depright = 1;
depleft = 1+TreeDepth(root.left);
depright = 1+TreeDepth(root.right);
return depleft>depright?depleft:depright;
}
}
解法2:层次遍历,使用队列辅助实现
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null)return 0;
//层次遍历,使用队列辅助实现
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int depth=0;
int cnt=0;
int nextcnt=1;
queue.add(root); //根节点加入队列
while(queue.size()!=0){
TreeNode top = queue.poll(); //Queue 中 remove() 和 poll()都是用来从队列头部删除一个元素并返回。
//在队列元素为空的情况下,remove() 方法会抛出NoSuchElementException异常,poll() 方法只会返回 null 。
cnt++;
if(top.left!=null){
queue.add(top.left);
}
if(top.right!=null){
queue.add(top.right);
}
if(cnt==nextcnt){ //当删除元素的数量等于该层结点数时,换下一层遍历
nextcnt = queue.size();
cnt=0;
depth++;
}
}
return depth;
}
}