Binary Trees
1 / 9
1
/ \
2 3
/ \
4 5
func solve(root *TreeNode) Result {
if root == nil {
return baseValue
}
left := solve(root.Left)
right := solve(root.Right)
return combine(root.Val, left, right)
}
Think: what do I need from children?
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return 1 + max(
maxDepth(root.Left),
maxDepth(root.Right),
)
}
"My depth = 1 + deeper child"
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}
Swap at every node.
Left subtree < Node < Right subtree
5
/ \
3 7
/ \
1 4
Inorder traversal = sorted order
Pass valid range down:
func validate(node, min, max) bool {
if node == nil { return true }
if node.Val <= min || node.Val >= max {
return false
}
return validate(node.Left, min, node.Val) &&
validate(node.Right, node.Val, max)
}
func LCA(root, p, q) *TreeNode {
if root == nil || root == p || root == q {
return root
}
left := LCA(root.Left, p, q)
right := LCA(root.Right, p, q)
if left != nil && right != nil {
return root
}
if left != nil { return left }
return right
}
| Operation | Time | Space |
|---|---|---|
| Traversal | O(n) | O(h) |
| Max Depth | O(n) | O(h) |
| Validate BST | O(n) | O(h) |
| LCA | O(n) | O(h) |
h = height (log n balanced, n skewed)