LeetCode 104. Maximum Depth of Binary Tree
原题链接在这里:https://leetcode.com/problems/maximum-depth-of-binary-tree/
题目:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
题解:
左右最大深度+1记为当前node maximum depth.
终止条件是root == null, 返回0.
Time Complexity: O(n), n is the number of nodes in the tree. Space: O(logn).
AC 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 public class Solution { 11 public int maxDepth(TreeNode root) { 12 if(root == null){ 13 return 0; 14 } 15 return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 16 } 17 }
AC JavaScript:
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val) { 4 * this.val = val; 5 * this.left = this.right = null; 6 * } 7 */ 8 /** 9 * @param {TreeNode} root 10 * @return {number} 11 */ 12 var maxDepth = function(root) { 13 if(!root){ 14 return 0; 15 } 16 17 return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 18 };
AC C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int maxDepth(TreeNode* root) { 15 if(!root){ 16 return 0; 17 } 18 19 return 1 + max(maxDepth(root->left), maxDepth(root->right)); 20 } 21 };
AC Python:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, val=0, left=None, right=None): 4 # self.val = val 5 # self.left = left 6 # self.right = right 7 class Solution: 8 def maxDepth(self, root: Optional[TreeNode]) -> int: 9 if not root: 10 return 0 11 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
跟上Balanced Binary Tree, Minimum Depth of Binary Tree, Diameter of Binary Tree, Smallest Subtree with all the Deepest Nodes, Height of Binary Tree After Subtree Removal Queries.