题目描述:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:1.递归思想,如果一棵树只有根节点,则深度为1,如果有左子树或右子树,则深度为左子树和右子树的深度最大值+1.
2.层次遍历,用nextcount记录每层节点的个数,count记录该层的节点是否全部出队列,如果全部出队列,则depth + 1。
代码一:
/**
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) {
if(root==null){
return 0;
}
int nLelt=TreeDepth(root.left);
int nRight=TreeDepth(root.right);
return nLelt>nRight?(nLelt+1):(nRight+1);
}
}
代码二:
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode pRoot)
{
if(pRoot == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(pRoot);
//nextCount记录每层节点数,当count值等于nextCount值时说明该层遍历完,深度+1
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;
}
}