forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
leaf-similar-trees.cpp
40 lines (38 loc) · 957 Bytes
/
leaf-similar-trees.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<TreeNode*> s1{root1} , s2{root2};
while (!s1.empty() && !s2.empty()) {
if (dfs(s1) != dfs(s2)) {
return false;
}
}
return s1.empty() && s2.empty();
}
private:
int dfs(vector<TreeNode*>& s) {
while (true) {
const auto node = s.back(); s.pop_back();
if (node->right) {
s.emplace_back(node->right);
}
if (node->left) {
s.emplace_back(node->left);
}
if (!node->left && !node->right) {
return node->val;
}
}
}
};