题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大
深度 3 。
代码实现
class Solution {
public int maxDepth(TreeNode root) {
// if(root == null) return 0;
// int left = maxDepth(root.left);
// int right = maxDepth(root.right);
// return Math.max(left, right) + 1;
if(root == null) return 0;
LinkedList<TreeNode> queue = new LinkedList<>();
LinkedList<TreeNode> tmp;
queue.add(root);
int count = 0;
while(!queue.isEmpty()){
tmp = new LinkedList<TreeNode>();
for(TreeNode node : queue){
if(node.left != null) tmp.add(node.left);
if(node.right != null) tmp.add(node.right);
}
count++;
queue = tmp;
}
return count;
}
}

687

被折叠的 条评论
为什么被折叠?



