Leetcode Tree problem collection (1)
- 104.Maximum Depth of Binary Tree
- 98.Validate Binary Search Tree
- 101.Symmetric Tree
- 102.Binary Tree Level Order Traversal
- 108.Convert Sorted Array to Binary Search Tree
Inorder (Left, Root, Right)
Preorder (Root, Left, Right)
Postorder (Left, Right, Root)
104. Maximum Depth of Binary Tree
DFS:1
2
3
4
5
6
7
8
9def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
left, right = 0, 0
if root.left:
left = self.maxDepth(root.left)
if root.right:
right = self.maxDepth(root.right)
return max(left, right) + 1
BFS:1
2
3
4
5
6
7
8
9
10
11
12
13def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
q = [(root, 1)]
depth = 0
while q:
cur, d = q.pop()
depth = max(d, depth)
if cur.left:
q.append((cur.left, d + 1))
if cur.right:
q.append((cur.right, d + 1))
return depth
98. Validate Binary Search Tree
This one is interesting1
2
3
4
5
6def isValidBST(self, root: TreeNode, floor=float('-inf'), ceil = float('inf')) -> bool:
if not root:
return True
if floor < root.val < ceil:
return self.isValidBST(root.left, floor, root.val) and self.isValidBST(root.right, root.val, ceil)
return False
101. Symmetric Tree
1 | def isSymmetric(self, root: TreeNode) -> bool: |
102. Binary Tree Level Order Traversal
BFS
1 | def levelOrder(self, root: TreeNode) -> List[List[int]]: |
DFS
1 | def levelOrder(self, root: TreeNode) -> List[List[int]]: |
108. Convert Sorted Array to Binary Search Tree
Typical DFS1
2
3
4
5
6
7
8
9def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums:
return None
i = int(len(nums) / 2)
node = TreeNode(nums[i])
node.left = self.sortedArrayToBST(nums[: i])
node.right = self.sortedArrayToBST(nums[i + 1: ])
return node