题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路
两种实现方式:递归式和非递归式;
1. 递归式:要算这棵树的深度,那么就等于需要算出它左子树的深度和右子树的深度后取最大的,然后在加1;
2. 非递归式:此时就需要借助二叉树的层序遍历,没遍历完一层,加1,最后返回二叉树的深度;
代码实现
1.递归式
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
return 1+Math.max(TreeDepth(root.left),TreeDepth(root.right));
}
2.非递归式
public int TreeDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if(root == null){
return 0;
}else{
queue.offer(root);
}
//记录当前的数量
int cnt=0;
//二叉树的深度
int depth = 0;
//记录每层的数量
int nextCount = 1;
while(!queue.isEmpty()){
TreeNode node = queue.poll();
cnt++;
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
//需要将这一层输出完,深度在加1
if(cnt == nextCount){
depth++;
cnt = 0;
nextCount = queue.size();
}
}
return depth;
}