给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
返回它的最大深度 3 。
方法一:递归
当前树的最大深度为左右子树的最大深度加一,左右子树又以同样的方式进行计算。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public int maxDepth(TreeNode root) { if(root == null){ return 0; } if(root.left == null && root.right == null){ return 1; } return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } }
|
时间复杂度O(n),树中的每个结点被访问一次。
空间复杂度O(h),h 为树的高度。
方法二:层次遍历
我们可以使用层次遍历来计算二叉树的深度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
class Solution { public int maxDepth(TreeNode root) { if(root == null){ return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int ans = 0; while(!queue.isEmpty()){ int size = queue.size(); while(size > 0){ TreeNode t = queue.poll(); if(t.left != null){ queue.offer(t.left); } if(t.right != null){ queue.offer(t.right); } --size; } ++ans; } return ans; } }
|
时间复杂度O(n),空间复杂度最坏O(n)。