maximum_depth_of_binary_tree
1from utils import TreeNode 2from typing import Optional 3 4 5# @leet start 6class Solution: 7 def maxDepth(self, root: Optional[TreeNode], depth: int = 0) -> int: 8 """ 9 To find the maximum depth of a tree, we can divide it into subproblems. 10 1. If the root is null, the depth is 0. 11 2. If the root is non-null, the depth is the maximum of the left and right 12 sutbrees + 1. 13 We apply that rule throughout the tree to get the depth. 14 """ 15 if not root: 16 return depth 17 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) 18 19 20# @leet end 21 22 23def test(): 24 assert 2 + 2 == 4
class
Solution:
7class Solution: 8 def maxDepth(self, root: Optional[TreeNode], depth: int = 0) -> int: 9 """ 10 To find the maximum depth of a tree, we can divide it into subproblems. 11 1. If the root is null, the depth is 0. 12 2. If the root is non-null, the depth is the maximum of the left and right 13 sutbrees + 1. 14 We apply that rule throughout the tree to get the depth. 15 """ 16 if not root: 17 return depth 18 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
8 def maxDepth(self, root: Optional[TreeNode], depth: int = 0) -> int: 9 """ 10 To find the maximum depth of a tree, we can divide it into subproblems. 11 1. If the root is null, the depth is 0. 12 2. If the root is non-null, the depth is the maximum of the left and right 13 sutbrees + 1. 14 We apply that rule throughout the tree to get the depth. 15 """ 16 if not root: 17 return depth 18 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
To find the maximum depth of a tree, we can divide it into subproblems.
- If the root is null, the depth is 0.
- If the root is non-null, the depth is the maximum of the left and right sutbrees + 1. We apply that rule throughout the tree to get the depth.
def
test():