Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 3
Example 2:
Input: root = [1,null,2] Output: 2
Example 3:
Input: root = [] Output: 0
Example 4:
Input: root = [0] Output: 1
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -100 <= Node.val <= 100
二叉树最大深度。
题意很简单,给一个二叉树,求它的最大深度。这是后序遍历的基础题,直接上代码。影子题543。
时间O(n)
空间O(h) - 树的高度
Java递归实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int maxDepth(TreeNode root) { 12 // corner case 13 if (root == null) { 14 return 0; 15 } 16 // normal case 17 int leftMax = maxDepth(root.left); 18 int rightMax = maxDepth(root.right); 19 return Math.max(leftMax, rightMax) + 1; 20 } 21 }
Java BFS实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int maxDepth(TreeNode root) { 18 // corner case 19 if (root == null) { 20 return 0; 21 } 22 // normal case 23 int count = 0; 24 Queue<TreeNode> queue = new LinkedList<>(); 25 queue.offer(root); 26 while (!queue.isEmpty()) { 27 int size = queue.size(); 28 for (int i = 0; i < size; i++) { 29 TreeNode cur = queue.poll(); 30 if (cur.left != null) { 31 queue.offer(cur.left); 32 } 33 if (cur.right != null) { 34 queue.offer(cur.right); 35 } 36 } 37 count++; 38 } 39 return count; 40 } 41 }
JavaScript DFS实现
1 /** 2 * @param {TreeNode} root 3 * @return {number} 4 */ 5 var maxDepth = function(root) { 6 if (root === null) return 0; 7 let leftMax = maxDepth(root.left); 8 let rightMax = maxDepth(root.right); 9 return Math.max(leftMax, rightMax) + 1; 10 };
相关题目
104. Maximum Depth of Binary Tree