Problem Description
Given two binary trees, determine if they are leaf-similar. Two trees are considered leaf-similar if their leaf value sequence (the values of the leaves from left to right) is the same.
Key Insights
- Collect the leaf values from each tree in a left-to-right order.
- Use Depth-First Search (DFS) to traverse the trees recursively and gather only the leaf node values.
- Compare the two resulting leaf value lists; if they are identical, the trees are leaf-similar.
Space and Time Complexity
Time Complexity: O(n) for each tree, where n is the number of nodes; overall O(n1 + n2). Space Complexity: O(n) for storing the leaf values and potential recursion stack.
Solution
We can solve the problem by performing a DFS traversal on each tree to collect the leaf nodes. A leaf is defined as a node with no left or right children. After collecting the leaf nodes from both trees in order, we simply compare the two lists. Key data structures:
- Arrays (or lists) to store the sequence of leaf values.
- Recursion stack for the DFS algorithm. Algorithmic approach:
- Define a helper function that traverses the tree recursively.
- When a leaf node is encountered (both left and right child are null), add its value to the list.
- Compare the two resulting lists from each tree. If they are identical, return true; otherwise, return false.