{x}
blog image

Boundary of Binary Tree

Solution Explanation: Boundary of Binary Tree

This problem asks to find the boundary of a binary tree. The boundary consists of the root, the left boundary (excluding leaf nodes), the leaves (from left to right), and the right boundary (excluding leaf nodes, in reversed order).

The solution uses Depth-First Search (DFS) to traverse the tree and collect the nodes that constitute the boundary. It's broken down into three main parts: left boundary, leaves, and right boundary.

Algorithm:

  1. Base Case: If the tree has only one node (root), return a list containing only the root's value.

  2. Left Boundary:

    • Start at the root's left child.
    • Add the node's value to the left list.
    • If the current node has a left child, recursively call the DFS function on the left child.
    • Otherwise, if it has a right child, recursively call the DFS function on the right child. This handles cases where the left boundary might need to go right to continue down the boundary. This stops when it reaches a leaf.
  3. Leaves:

    • Perform a standard DFS traversal to collect all leaf nodes. A leaf node is one without left or right children. Add leaf nodes to the leaves list.
  4. Right Boundary:

    • Start at the root's right child.
    • Add the node's value to the right list.
    • If the current node has a right child, recursively call the DFS on the right child.
    • Otherwise, if it has a left child, recursively call the DFS on the left child. (Similar logic as left boundary, but going right first). This stops when it reaches a leaf.
  5. Concatenation: Finally, concatenate the root, the left boundary, the leaves, and the reversed right boundary to form the complete boundary.

Time Complexity: O(N), where N is the number of nodes in the tree. The DFS traversal visits each node at most once.

Space Complexity: O(N) in the worst case, due to the recursive call stack and the lists used to store the left boundary, leaves, and right boundary. In a skewed tree, the stack could reach a depth of N.

Code Explanation (Python):

The Python code provided implements this algorithm efficiently. The dfs function handles the recursive traversal for each part of the boundary. The i parameter in dfs indicates which part of the boundary is being processed (0 for left, 1 for leaves, 2 for right). The code then combines these lists to form the final result.

Code Explanation (Other Languages):

The code in Java, C++, Go, TypeScript, and Javascript follows the same logic, adapting the syntax and data structures specific to each language. The core algorithm remains consistent across all implementations. Note that the recursive calls in C++ use a lambda function for concise self-referential calls. Go uses a similar approach with anonymous functions.