[LeetCode] Leaf-Similar Trees

872. Leaf-Similar Trees

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
void dfs(TreeNode* node, vector<int>& A) {
if(!node) return;
if(!node->left and !node->right) {
A.push_back(node->val);
}
dfs(node->left,A);
dfs(node->right,A);
}
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> A,B;
dfs(root1,A);
dfs(root2,B);
return A == B;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/08/PS/LeetCode/leaf-similar-trees/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.