0%

leetcode2-104. Maximum Depth of Binary Tree

1. problem

  1. an unbalanced binary tree,
  2. find out maximum path.

2. init

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:

3. thought

  1. if node is null, return 0
  2. check root’s left/right
  3. return 1 + max of Left/right node

4. trouble

each node do their job.

5.final solution

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None: return 0
return max(1+ self.maxDepth(root.left),1+ self.maxDepth(root.right))