Home

Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree Solutions Solution 1 Recursively get 1 + max(left, right) Solution 2 Use stack to keep track of node and its level. Use a variable to keep max_level, update it each time reaching a leaf.

Read more

Binary Tree Maximum Path Sum

124. Binary Tree Maximum Path Sum Solutions Comparison is needed when: Decide if we should update current maximum path sum. Decide left or right child can be part of the maximum path. Keep a global variable to keep track of current maximum path sum. Helper function returns maximum path sum of left / right child + current...

Read more

Course Schedule

207. Course Schedule Solutions Use DFS to traverse through all courses. Mark a course as visited if all its pre-requisites are visited. Any course that was not visited returns False.

Read more

Clone Graph

133. Clone Graph Solutions Maintain a node dictionary that stores all constructed node. For each new node introduced, loop through all its neighbours to find the node corresponding to the neighbour. Need to use helper function.

Read more

Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal Solutions The solution is similar to divide and conquer. Find the root by using pre-order traversal. Find the root’s index in in-order traversal. Divide in-order by the index and continue. Optimization Can use dictionary to store the index of in-order array {num: idx} and use i...

Read more

Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree Solutions Serialize Print the tree in pre-order traversal. Explicitly noted down null nodes. Deserialize Use queue to deserialize the pre-order traversal. Since null node is stored, we know we should stop when null is encountered.

Read more