tree-christmasTree

Notes and typical questions for Tree related problems

,Notes

  • BFS vs DFS

    • DFS

      • Path-related problems because it can examine each path before moving on to the next.

    • BFS

      • Level-related problem.

  • As we know, the maximal number of nodes in N-ary tree of HH height would be NH+1N^{H+1}

    • 1+N+N2+....+NH1+N+N^2+....+N^H (等比数列)

Typical Questions (53)

Preorder/Inorder/Postorder Traversal (4)

  • LC 144. Binary Tree Preorder Traversal

    • Order: Middle, Left, Right

    • Recursive way: Basic

    • 🟠 Iterative way: It is straightforward to use a stack

  • LC 145. Binary Tree Postorder Traversal

    • Order: Left, Right, Middle

    • Recursive way: Basic

    • Iterative way

      • Method 1: Depend on preorder traversal (Need to modify a little bit: swap left and right, then swap the entire result at the end)

      • 🟠 Method 2: Do postorder traversal from scratch. Need one variable to store the previously polled TreeNode so that we can know if the current should be polled during this visit.

  • LC 94. Binary Tree Inorder Traversal

    • Order: Left, Middle, Right

    • Recursive way: Basic

    • 🔴 Iterative way: VERY HARD to recall the correct solution. In addition to the stack itself, we need another variable (TreeNode pointer) to traverse the tree in inorder. This variable can notify us whether we should poll a node in the stack (collect the result) or continue exploring to the left.

  • LC 173. Binary Search Tree Iterator

🧩 Level Order Traversal (12)

  • Notes

    • Space complexity

      • Let w be the maximum number of nodes at any level (the tree’s width). The queue size is O(w)O(w).

        • For a binary tree, wnw≤n and in the worst case, wn/2w≤⌈n/2⌉ (when the last level is ~n/2n/2 nodes, e.g., a complete/perfect tree).

  • LC 102. Binary Tree Level Order Traversal

    • Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(n)O(n)

      • Space complexity = O( max number of nodes on a level), for a full and complete binary tree(worst case) last level which has all the leaf nodes will have the max number of nodes. Number of leaf nodes is given by (n+1)/2, so ignoring the constants makes the space complexity O(N)

  • LC 107. Binary Tree Level Order Traversal II

  • LC 199. Binary Tree Right Side View

    • Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(w+height)O(w+height), where ww is the number of nodes in the widest level of the binary tree.

  • LC 637. Average of Levels in Binary Tree

  • LC 429. N-ary Tree Level Order Traversal

  • LC 515. Find Largest Value in Each Tree Row

  • LC 116. Populating Next Right Pointers in Each Node

    • Need to change the visit order for each level

  • LC 117. Populating Next Right Pointers in Each Node II

  • LC 104. Maximum Depth of Binary Tree

    • Method 1: Recursive way

    • Method 2: Iterative way (level order traversal)

  • LC 111. Minimum Depth of Binary Tree

    • Be careful about the definition of Minimum Depth

    • Method 1: Recursive way

    • Method 2: Iterative way (level order traversal)

  • LC 559. Maximum Depth of N-ary Tree

    • Method 1: Recursive way

    • Method 2: Iterative way (level order traversal)

  • LC 1161. Maximum Level Sum of a Binary Tree

  • LC 103. Binary Tree Zigzag Level Order Traversal

  • LC 339. Nested List Weight Sum

  • LC 314. Binary Tree Vertical Order Traversal

Tree Manipulation (3)

Tree Comparison (4)

  • LC 101. Symmetric Tree

    • Just need to do traversal for 2 trees at the same time.

  • LC 100. Same Tree

    • Similar to the above one

  • 🔴 LC 572. Subtree of Another Tree

    • Depends on "LC 100. Same Tree" in a helper function way

    • Be careful about null check

    • Be careful about which function gets called during recursion.

  • LC 617. Merge Two Binary Trees

Tree Property (6)

  • LC 222. Count Complete Tree Nodes

    • Optimal Answerarrow-up-right. The best solution is O(lognlogn)O(logn * logn)

      • Check how to calculate this time complexity in the LC submission notes

      • Another way to understand it: T(n)=T(n/2)+O(logn)T(n)=T(n/2)+O(logn) => lognlognlogn * logn (ask GPT why)

  • 🟠 LC 110. Balanced Binary Tree

    • Be sure to skillfully utilize the return value of the recursive function to get the final result in ONE traversal

    • Be sure to return the result in advance to speed up the calculation

  • 🌟 LC 236. Lowest Common Ancestor of a Binary Tree

    • Assumptions: p != q, p and q will exist in the tree, All Node.val are unique.

    • 2 cases:

      1. p and q has LCA which is another node s.

      2. One of p and q is LCA for another node.

    • Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(height)O(height)

  • LC 1650. Lowest Common Ancestor of a Binary Tree III

    • I can’t believe I didn’t realize this problem is the same as LC 160 !!!

    • Approach 1 using Set: Answerarrow-up-right. TC: O(height)O(height), SC: O(height)O(height)

    • 👍 Approach 2 without Set: Optimal Answerarrow-up-right. TC: O(height)O(height), SC: O(1)O(1)

  • LC 1257. Smallest Common Region

    • Use HashMap and HashSet to simulate the LCA process.

    • Optimal Answerarrow-up-right.

      • Let mm be the number of region arrays, and let nn be the number of regions in each array.

        • TC: O(mn)O(m*n)

        • SC: O(mn)O(m*n)

  • 🔴 LC 2458. Height of Binary Tree After Subtree Removal Queries

    • Idea: Try to think in the way of checking the height of each node by preorder traversal

    • Optimal Answerarrow-up-right. TC: O(n+q)O(n+q), SC: O(n)O(n)

  • LC 2265. Count Nodes Equal to Average of Subtree

Tree Path (10)

  • LC 257. Binary Tree Paths

    • Be careful about how to store results during traversal

    • This is kind of a backtracking problem. Remember to reset the status in each recursion level

    • Optimal Answer. TC: O(nlogn)O(n*log{n}), SC: O(n)O(n)

  • LC 112. Path Sum

  • LC 113. Path Sum II

    • Not difficult but easy to make mistakes when storing results.

  • 🌟 🟠 LC 437. Path Sum III

    • It's kind of hard to figure out the solution using DFS + HashMap

    • Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(height)O(height)

  • LC 513. Find Bottom Left Tree Value

    • Method 1: Iterative way. Easy to implement and understand.

    • Method 2: Recursive way. Do it in ONE traversal. Remember that all traversal methods (Pre/In/Post order) always visit the left node first by default. This can simplify recursion logic at each level.

  • LC 404. Sum of Left Leaves

    • The solution without a helper function is kind of hard to understand. Having a helper function with a flag may be a better way.

  • LC 1448. Count Good Nodes in Binary Tree

  • LC 1372. Longest ZigZag Path in a Binary Tree

  • 🔴 124. Binary Tree Maximum Path Sum

    • I made it by myself! The editorial solution is more elegant in implementation. (I failed to make it the second time....)

    • Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(n)O(n)

  • LC 543. Diameter of Binary Tree

  • LC 129. Sum Root to Leaf Numbers

    • Answerarrow-up-right. TC: O(n)O(n), SC: O(height)O(height)

      • The optimal answer is to use the Morris Algorithm with constant space, but I feel that's too complicated to write.

Construct Binary Tree (3)

  • Notes: Not difficult but easy to make mistakes in implementation

  • LC 106. Construct Binary Tree from Inorder and Postorder Traversal

  • LC 105. Construct Binary Tree from Preorder and Inorder Traversal

  • LC 654. Maximum Binary Tree

Tree Leaf (1)

BST (10)

  • Notes

    • 🧩 Pattern 1: Traverse BST with prev node in the recursive way (LC 98, 530, 501)

    • 🧩 Pattern 2: Traverse BST with stack in the iterative way (LC 98, 230)

  • 🌟 LC 700. Search in a Binary Search Tree

  • LC 98. Validate Binary Search Tree

    • Method 1: Use an array to store all elements visited by inorder traversal. Then check if each element in the array is bigger than the previous one. Very easy but needs extra space

    • 👍 Method 2: Do validation during inorder traversal with 2 pointers. 1 pointer points to the current node. Another pointer points to the previous node (based on in-order sequence). In this way, we can bypass that limitation issue. Be careful to make that prev node a class variable instead of a function argument! The prev node is very hard to update if we pass it through the function argument. Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(h)O(h)

    • Method 3: Use range to validate left and right nodes. Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(h)O(h)

  • LC 530. Minimum Absolute Difference in BST

  • 🟠 LC 501. Find Mode in Binary Search Tree

    • Need some code skills to resolve it in 1 traversal

    • Need to do inorder traversal with prev pointer

    • If maxCount > count, we must clear the result list. For example [1, null, 2, 2], when we meet 1st element 2, we will keep both 1 and 2 in the result list. Then when we meet 2nd element 2, although 2 already in the result list, we still need to clear it due to the element 1.

    • Optimal Answerarrow-up-right. TC: O(n)O(n), SC: O(h)O(h)

  • 🌟 🟠 LC 235. Lowest Common Ancestor of a Binary Search Tree

    • Assumptions: p != q, p and q will exist in the tree, All Node.val are unique.

    • It's very easy to not fully use the property of BST and miss best solution. The best solution is very short by fully using the property of BST!

    • Recursive Answerarrow-up-right. TC: O(n)O(n), SC: O(h)O(h)

  • LC 701. Insert into a Binary Search Tree

    • Assumptions: It is guaranteed that the new value does not exist in the original BST.

    • It's very easy to resolve if you insert a node as a leaf node.

  • 🌟 LC 450. Delete Node in a BST

    • The logic is straightforward. 5 cases in total. The first 4 cases are actually similar. Most code is for handling the 5th case.

      • No targetnode

      • targetNode.left == null && targetNode.right == null

      • targetNode.left != null && targetNode.right == null

      • targetNode.left == null && targetNode.right != null

      • targetNode.left != null && targetNode.right != null

    • Optimal Answerarrow-up-right. TC: O(height)O(height), SC: O(height)O(height)

  • LC 669. Trim a Binary Search Tree

  • LC 538. Convert BST to Greater Tree

  • LC 230. Kth Smallest Element in a BST

    • It's important to know both recursive and iterative ways.

    • Approach 1 using the recursive way

      • TC: O(h+k)O(h+k). O(H) to reach the smallest node in the BST. O(k) to find the kth smallest from there, doing an inorder search.

      • SC: O(h)O(h)

    • Approach 2 using the iterative way: Optimal Answerarrow-up-right. TC: O(h+k)O(h+k), SC: O(h)O(h)

Last updated