Tree
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 H height would be NH+1
1+N+N2+....+NH (等比数列)
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
Optimal Answer. TC: O(n), SC: O(h) -> I think SC is O(h) instead of O(n) listed in leetcode solution.
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)
Optimal Answer. TC: O(n), SC: O(h)
🟠 Method 2: Do postorder traversal from scratch. Need one variable to store the previously polled
TreeNodeso that we can know if the current should be polled during this visit.Optimal Answer. TC: O(n), SC: O(n)
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.
Optimal Answer. TC: O(n), SC: O(n)
LC 173. Binary Search Tree Iterator
Optimal Answer. TC for each call in average: O(1), SC: O(h)
🧩 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).
For a binary tree, w≤n and in the worst case, w≤⌈n/2⌉ (when the last level is ~n/2 nodes, e.g., a complete/perfect tree).
LC 102. Binary Tree Level Order Traversal
Optimal Answer. TC: O(n), SC: 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 Answer. TC: O(n), SC: O(w+height), where w 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
Approach 1 with classic BFS queue: Answer. TC: O(n), SC: O(n)
Need to change the visit order for each level
👍 🟠 Approach 2: Optimal Answer. TC: O(n), SC: O(1)
LC 104. Maximum Depth of Binary Tree
Method 1: Recursive way
Optimal Answer. TC: O(n), SC: O(Height)
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
Optimal Answer. TC: O(n), SC: O(w), where w is the number of nodes in the widest level of the binary tree.
⚪ LC 103. Binary Tree Zigzag Level Order Traversal
Use
LinkedListto avoid complicated logic.Optimal Answer. TC: O(n), SC: O(n)
LC 339. Nested List Weight Sum
Optimal Answer. TC: O(n), SC: O(n)
LC 314. Binary Tree Vertical Order Traversal
Optimal Answer. TC: O(n), SC: O(n)
Tree Manipulation (3)
🌟 ⚪ LC 226. Invert Binary Tree
Make the solution accepted in the submission!!!
Optimal Answer. TC: O(n), SC: O(h)
⚪ LC 1110. Delete Nodes And Return Forest
Optimal Answer. TC: O(n), SC: O(n)
LC 114. Flatten Binary Tree to Linked List
⚪ Approach 1: Recursive solution. TC: O(N), SC: O(N). Post-order traversal can have shorter code than pre-order traversal.
Approach 2: Iterative solution using a stack. TC: O(N), SC: O(N).
👍 🟠 Approach 3: Optimal iterative solution with the same ideology as Morris Traversal.
TC: O(N). Each node will be processed at most twice.
SC: O(1)
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 Answer. The best solution is 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) => logn∗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,pandqwill exist in the tree, AllNode.valare unique.2 cases:
pandqhas LCA which is another nodes.One of
pandqis LCA for another node.
Optimal Answer. TC: O(n), SC: 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: Answer. TC: O(height), SC: O(height)
👍 Approach 2 without Set: Optimal Answer. TC: O(height), SC: O(1)
LC 1257. Smallest Common Region
Use
HashMapandHashSetto simulate the LCA process.Let m be the number of region arrays, and let n be the number of regions in each array.
TC: O(m∗n)
SC: 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 Answer. TC: O(n+q), SC: O(n)
LC 2265. Count Nodes Equal to Average of Subtree
Optimal Answer. TC: O(n), SC: O(n)
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(n∗logn), SC: O(n)
⚪ LC 112. Path Sum
Be careful about corner case: empty tree
Optimal Answer. TC: O(n), SC: O(n)
⚪ 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 Answer. TC: O(n), SC: 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
Do not use extra space!
Optimal Answer. TC: O(n), SC: O(height)
⚪ LC 1372. Longest ZigZag Path in a Binary Tree
Optimal Answer. TC: O(n), SC: O(height)
🔴 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 Answer. TC: O(n), SC: O(n)
LC 543. Diameter of Binary Tree
Optimal Answer. TC: O(n), SC: O(height)
LC 129. Sum Root to Leaf Numbers
Answer. TC: O(n), SC: 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
Optimal Answer. TC: O(n), SC: O(n)
⚪ LC 105. Construct Binary Tree from Preorder and Inorder Traversal
Optimal Answer. TC: O(n), SC: O(n)
Tree Leaf (1)
LC 872. Leaf-Similar Trees
Optimal Answer. TC: O(n), SC: O(n)
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
Optimal Answer. TC: O(height), SC: O(height)
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
prevnode a class variable instead of a function argument! Theprevnode is very hard to update if we pass it through the function argument. Optimal Answer. TC: O(n), SC: O(h)Method 3: Use range to validate left and right nodes. Optimal Answer. TC: O(n), SC: O(h)
LC 530. Minimum Absolute Difference in BST
Similar to LC 98
Optimal Answer. TC: O(n), SC: O(h)
🟠 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 element2, we will keep both1and2in the result list. Then when we meet 2nd element2, although2already in the result list, we still need to clear it due to the element1.Optimal Answer. TC: O(n), SC: O(h)
🌟 🟠 LC 235. Lowest Common Ancestor of a Binary Search Tree
Assumptions:
p != q,pandqwill exist in the tree, AllNode.valare 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 Answer. TC: O(n), SC: 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
targetnodetargetNode.left == null && targetNode.right == nulltargetNode.left != null && targetNode.right == nulltargetNode.left == null && targetNode.right != nulltargetNode.left != null && targetNode.right != null
Optimal Answer. TC: O(height), SC: O(height)
⚪ LC 669. Trim a Binary Search Tree
LC 538. Convert BST to Greater Tree
Try to resolve it without a helper function
Optimal Answer. TC: O(n), SC: O(h)
⚪ 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) to reach the smallest node in the BST. O(k) to find the kth smallest from there, doing an inorder search.
SC: O(h)
Approach 2 using the iterative way: Optimal Answer. TC: O(h+k), SC: O(h)
Last updated