Guidelines
Most of the problems in the category deal with trees since we have use dfs to solve most of those problems. If you have a recursive structure like a tree (node, part of a tree is also a tree leading to recursions) first think of the subtree as simple node, and apply the operation on it, then think of it as a subtree and call the main function just like you did on the root of tree. Think if you can use additional info on the node not available in the basic implementation like number of children, parent or any other relation.
Three tree traversals:
- Inorder traversal (left, root, right) Kth Smallest Element in a BST
if(root.left != null) helper(root.left, result);
if(--result.count == 0){
result.value = root.val;
return;
}
if(root.right != null) helper(root.right, result);
- Postorder (left, right, root) Maximum Depth of Binary Tree
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
- Preorder (root, left, right) Merge Two Binary Trees
root.val = root1.val + root2.val;
root.left = helper(root1.left, root2.left, new TreeNode());
root.right = helper(root1.right, root2.right, new TreeNode());
To build the tree from it's traversal we can use it's preorder and any of other two traversals (Construct Binary Tree from Preorder and Inorder Traversal) or just preorder with special mark for null nodes (Serialize and Deserialize Binary Tree).