Skip to content

Commit 7faefd1

Browse files
committed
add prob #872; iterative solution
1 parent 376f1ac commit 7faefd1

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

872_Leaf_Similar_Trees.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
Consider all the leaves of a binary tree.  From left to right order, the values of those leaves form a leaf value sequence.
3+
4+
5+
6+
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
7+
8+
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
9+
10+
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
11+
12+
 
13+
14+
Constraints:
15+
16+
Both of the given trees will have between 1 and 200 nodes.
17+
Both of the given trees will have values between 0 and 200
18+
19+
来源:力扣(LeetCode)
20+
链接:https://leetcode-cn.com/problems/leaf-similar-trees
21+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
22+
*/
23+
24+
#include <stack>
25+
#include <vector>
26+
using namespace std;
27+
28+
struct TreeNode {
29+
int val;
30+
TreeNode *left;
31+
TreeNode *right;
32+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
33+
};
34+
35+
class Solution {
36+
private:
37+
void leafSimilar(TreeNode* root, vector<int>& res){
38+
if(root==NULL) return;
39+
stack<TreeNode*> s;
40+
41+
s.push(root);
42+
while(!s.empty()){
43+
TreeNode* tmp_node = s.top(); s.pop();
44+
if((tmp_node->left==NULL)&&(tmp_node->right==NULL)) res.push_back(tmp_node->val);
45+
if(tmp_node->right) s.push(tmp_node->right);
46+
if(tmp_node->left) s.push(tmp_node->left);
47+
}
48+
49+
return;
50+
}
51+
public:
52+
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
53+
vector<int> res1, res2;
54+
leafSimilar(root1, res1);
55+
leafSimilar(root2, res2);
56+
57+
if(res1.size()!=res2.size()) return false;
58+
for (int i = 0; i < (int)res1.size(); ++i) {
59+
if(res1[i]!=res2[i]) return false;
60+
}
61+
return true;
62+
}
63+
};

0 commit comments

Comments
 (0)