DSA Master › Topic 11
Binary Trees
Nearly every tree problem follows one recursive question: "What does each child need to return so I can answer at this node?" Postorder DFS (children first) handles height, diameter and path sums. BFS with a queue handles anything level by level.
Concepts
- DFS
- BFS
- Preorder / inorder / postorder
- Level-order
- Tree construction
How to recognise it
- The answer depends on the left and right subtrees. Use postorder DFS.
- The problem talks about levels, depth order or the "view" from one side. Use BFS.
- You need to pass information down to children. Pass it as a parameter, preorder style.
Common pitfalls
- Handle the null root first.
- Separate what you return to the parent from the global answer you track. Max Path Sum depends on this.
Problems
- Maximum Depth of Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Same Tree (Easy)
- Balanced Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Path Sum (Easy)
- Path Sum II (Medium)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Serialize and Deserialize Binary Tree (Hard)
- Binary Tree Maximum Path Sum (Hard)
- Vertical Order Traversal of a Binary Tree (Hard)