← Home

872. Leaf-Similar Trees

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
872

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 872. Leaf-Similar Trees, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are build_leaf_values, leafSimilar, dfs.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Consider all the leaves of a binary tree.  From left to right order, the values of those leaves form a leaf value sequence.
03
04For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
05
06Two binary trees are considered leaf-similar if their leaf value sequence is the same.
07
08Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
09
10Note:
11
12Both of the given trees will have between 1 and 100 nodes.
13**/
14
15/**
16 * Definition for a binary tree node.
17 * struct TreeNode {
18 *     int val;
19 *     TreeNode *left;
20 *     TreeNode *right;
21 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
22 * };
23 */
24 
25//Runtime: 4 ms, faster than 57.23% of C++ online submissions for Leaf-Similar Trees.
26class Solution {
27public:
28    void build_leaf_values(TreeNode* root, vector<int>* leaf_values){
29        stack<TreeNode*> stk;
30        TreeNode* cur;
31        
32        stk.push(root);
33        while(!stk.empty()){
34            cur = stk.top();
35            stk.pop();
36            
37            if(cur->left==NULL && cur->right==NULL){
38                leaf_values->push_back(cur->val);
39            }else{
40                if(cur->right) stk.push(cur->right);
41                if(cur->left) stk.push(cur->left);
42            }
43        }
44    }
45    
46    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
47        vector<int> leaf_values1, leaf_values2;
48        
49        build_leaf_values(root1, &leaf_values1);
50        build_leaf_values(root2, &leaf_values2);
51        
52        if(leaf_values1==leaf_values2){
53            return true;
54        }else{
55            return false;
56        }
57    }
58};
59
60/**
61Approach 1: Depth First Search
62Intuition and Algorithm
63
64Let's find the leaf value sequence for both given trees. 
65Afterwards, we can compare them to see if they are equal or not.
66
67To find the leaf value sequence of a tree, we use a depth first search. 
68Our dfs function writes the node's value if it is a leaf, and then recursively explores each child. 
69This is guaranteed to visit each leaf in left-to-right order, as left-children are fully explored before right-children.
70
71//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Leaf-Similar Trees.
72class Solution {
73public:
74    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
75        vector<int> leaves1;
76        vector<int> leaves2;
77        dfs(root1, leaves1);
78        dfs(root2, leaves2);
79
80        return leaves1 == leaves2;
81    }
82
83    void dfs(TreeNode* node, vector<int>& leaves) {
84        if (node == NULL) return;
85        if (node->left == NULL && node->right == NULL)
86            leaves.push_back(node->val);
87        dfs(node->left, leaves);
88        dfs(node->right, leaves);
89    }
90};
91
92Complexity Analysis
93
94Time Complexity: O(T_1 + T_2), where T_1, T_2 are the lengths of the given trees.
95
96Space Complexity: O(T_1 + T_2), the space used in storing the leaf values. 
97 
98**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.