🚀 🚀Master Tree Patterns 🚀🚀
13138
Apr 14, 2024
May 18, 2024

1. Level order traversal

Basic Level Order Implementation
/*Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
*/
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>>ans;
        if(root==NULL)return ans;
        TreeNode* curr=root;
        queue<TreeNode*>q;
        q.push(root);
        
        while(q.empty()==false){
            int size=q.size();
            vector<int> curr;
            while(size--){
                auto x=q.front();
                q.pop();
                curr.push_back(x->val);
                if(x->left!=NULL) q.push(x->left);
                if(x->right!=NULL)q.push(x->right);
            }
            ans.push_back(curr);
        }
        return ans;
    }
};
  • BFS can be used to traverse a tree level wise . One key point to note is that we can control which way we want to traverse
    (either left to right or right to left) by deciding what goes inside queue first.
  • DFS can also be used to solve these type of problems by adding a level variable

102. Binary Tree Level Order TraversalSolution BFS/DFS
107. Binary Tree Bottom up Level Order Traversal
429. N-ary Tree Level Order Traversal
637. Average of Levels in Binary Tree
103. Binary Tree Zigzag Level Order Traversal
623. Add One Row at a given Level in a binary Tree
2415. Reverse Odd Levels of Binary Tree ✏️
2471. Minimum Number of Operations to Sort a Binary Tree by Level ✏️ CyclicSort+BFS

2. Depth/Height based

Note:Always check height is 0 or 1 indexed

104. Maximum Depth of Binary Tree 📝Classic DFS
111. Minimum Depth of Binary Tree 📝BFS intuitive
559. Maximum Depth of N-ary Tree

3. Tree construction

Inorder + Preorder => Unique tree
Inorder + Postorder => Unique tree
Postorder + Preorder => Multiple Trees possible

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal D&C
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal D&C
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ D&C
https://leetcode.com/problems/construct-string-from-binary-tree
https://leetcode.com/problems/maximum-binary-tree/ D&C Monotonic Stack

4. Counting

  1. Count nodes with some condtion
  2. Count Trees or subtrees

https://leetcode.com/problems/count-complete-tree-nodes/
https://leetcode.com/problems/count-good-nodes-in-binary-tree/
https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/
250.Count Univalue Subtrees [Premium] [CN]

5. Comparison on Two Trees

In these type of problem we generally run dfs/bfs simulataneously on both trees

100. Same TreeSolution DFS
101. Symmetric TreeSolution DFS
872. Leaf-Similar Trees
572. Subtree of Another Tree

6. Path

total number of paths between any two nodes in a binary tree with n nodes is:
n×(n−1) ​/2
For each starting node, there are n−1 other nodes in the tree to which it can connect, forming n−1 paths.

687. Longest Univalue Path
124. Binary Tree Maximum Path Sum H

7. Rooted Path (Root to leaves)

when a path starts from root and ends at leaf node

1022. Sum of Root To Leaf Binary Numbers path forms a binary number
129. Sum Root to Leaf Numbers path forms a number
257. Binary Tree Paths Backtracking
988. Smallest String Starting From Leaf
112. Path Sum

8. Tree Leaves

operations done on leaf nodes

https://leetcode.com/problems/sum-of-left-leaves/
https://leetcode.com/problems/deepest-leaves-sum
https://leetcode.com/problems/delete-leaves-with-a-given-value/

9. Ancestor

236. Lowest Common Ancestor of a Binary TreeSolution
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
https://leetcode.com/problems/kth-ancestor-of-a-tree-node/
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/

10. Iterative Tree Traversals

Iterative Inorder
Iterative Preorder
Iterative Postorder

11. Graph Creation

use this option when you need more freedom to move inside a tree

863. All Nodes Distance K in Binary Tree better alternatives might be available
310. Minimum Height Trees
834. Sum of Distances in Tree
2385. Amount of Time for Binary Tree to Be Infected

12. DP

337. House Robber III
894. All Possible Full Binary Trees
968. Binary Tree Cameras



BST (BINARY SEARCH TREE)

Inorder Traversal of a BST is always sorted so keep that in mind while solving bst problems.

https://leetcode.com/problems/search-in-a-binary-search-tree E
https://leetcode.com/problems/validate-binary-search-tree E
https://leetcode.com/problems/find-mode-in-binary-search-tree/ E
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ E
https://leetcode.com/problems/increasing-order-search-tree/ E
https://leetcode.com/problems/range-sum-of-bst/ E
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ E D&C
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree
LC.426 BST to sorted DLL(Premium) [CN]
285 Inorder Successor in BST [P] CN
https://leetcode.com/problems/minimum-absolute-difference-in-bst/
https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ Two BST
https://leetcode.com/problems/kth-smallest-element-in-a-bst
https://leetcode.com/problems/trim-a-binary-search-tree/ Trim
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
https://leetcode.com/problems/unique-binary-search-trees/ DP Catalan
https://leetcode.com/problems/delete-node-in-a-bst Textbook
https://leetcode.com/problems/insert-into-a-binary-search-tree/ Textbook **
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree LCA

Comments (6)