题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
方法一(DFS)
1.解题思路
先得到左子树高度,然后得到右子树高度,两者中较大的加1即为当前树的高度。树为空时,结束递归。实质上相当于走了一遍树的后续遍历。
2.代码实现
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;
}
}
3.复杂度分析
- 时间复杂度:需要遍历树中所有节点,所以时间复杂度为O(n)。
- 空间复杂度:最坏情况下,退化为链表,所以空间复杂度为O(n)。
方法二(BFS)
1.解题思路
利用队列进行层序遍历,每遍历完一层,高度加1,最后的高度即为整棵树的深度。
2.代码实现
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
Deque<TreeNode> queue=new LinkedList<>();
queue.offer(root);
int depth=0;
while(queue.size()>0){
int n=queue.size();
for(int i=0;i<n;i++){
TreeNode node=queue.poll();
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
}
depth++;
}
return depth;
}
}
3.复杂度分析
- 时间复杂度:需要遍历树中所有节点,所以时间复杂度为O(n)。
- 空间复杂度:需要容量为n的队列,所以空间复杂度为O(n)。
剑指offer全集入口: 请戳这里