BST
BST
Maximum Depth of Binary Tree Think of recursive DFS Use a depth-first search (DFS) traversal.
Return 1 + max(left_depth, right_depth)
to calculate the max depth.
Same Tree Compare nodes recursively Recursively check if the values at the
current node are the same and check
left and right subtrees using recursion.
Invert Binary Tree Swap left and right children recursively Recursively swap the left and right child
nodes for each node. Post-order or pre-
order traversal works.
Subtree of Another Tree Use DFS and check for identical subtree For each node in the main tree, check if
the subtree rooted at this node is
identical to the other tree using DFS.
Lowest Common Ancestor of a BST Use BST properties (left < root < right) Use the BST property to narrow down
the search space. Recur or iterate to
find the lowest common ancestor.
Binary Tree Level Order Traversal Use BFS to explore level by level Use Breadth-First Search (BFS) with a
queue. At each level, push all nodes of
the current level into a result list.
Validate Binary Search Tree Use DFS with bounds Perform an in-order traversal while
maintaining upper and lower bounds for
each node's value. Check if the values
are valid.
Kth Smallest Element in a BST In-order traversal for BST (sorted order) Perform in-order traversal of the BST
and return the k-th element. In-order
traversal returns nodes in sorted order.
Construct Binary Tree from Preorder Use recursion and array slicing The first element of the preorder array is
and Inorder Traversal the root. Recursively construct the left
and right subtrees from inorder array.
Binary Tree Maximum Path Sum Use post-order DFS to track max sum Recursively calculate the max path sum
at each node, considering both left and
right subtrees. Keep track of global max.
Serialize and Deserialize Binary Tree Use DFS/BFS for serialization Use DFS/BFS to serialize the tree into a
string and then use the same method to
deserialize it back into a tree structure.
Balanced Binary Tree Check height difference of subtrees Use post-order DFS to calculate heights
of subtrees. If the height difference is
more than 1, the tree is not balanced.
Diameter of Binary Tree Use post-order DFS Calculate the max diameter at each
node by finding the longest path
through its left and right children.
Symmetric Tree Check if left and right subtrees mirror Recursively compare the left and right
subtrees to check if they are symmetric
(mirror image of each other).
Binary Tree Right Side View Use BFS/DFS, track last node at each Use BFS and keep track of the last node
level at each level. In DFS, keep a record of
the depth and only add nodes at new
depths.