Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2530dd0

Browse files
Add files via upload
1 parent3463d81 commit2530dd0

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Leaf-Similar Trees.
2+
// Memory Usage: 13.3 MB, less than 88.89% of C++ online submissions for Leaf-Similar Trees.
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
classSolution
14+
{
15+
public:
16+
boolleafSimilar(TreeNode* root1, TreeNode* root2)
17+
{
18+
vector<int> leaf1;
19+
vector<int> leaf2;
20+
21+
traversal(leaf1, root1);
22+
traversal(leaf2, root2);
23+
24+
if (leaf1.size() != leaf2.size())
25+
{
26+
returnfalse;
27+
}
28+
else
29+
{
30+
for (int i =0; i < leaf1.size(); ++i)
31+
{
32+
if (leaf1[i] != leaf2[i])
33+
{
34+
returnfalse;
35+
}
36+
}
37+
returntrue;
38+
}
39+
}
40+
private:
41+
voidtraversal(vector<int>& res, TreeNode* root)
42+
{
43+
stack<TreeNode*> memo;
44+
45+
while (!memo.empty() || root)
46+
{
47+
while (root)
48+
{
49+
if (root->left ==nullptr && root->right ==nullptr)
50+
{
51+
res.push_back(root->val);
52+
}
53+
memo.push(root);
54+
root = root->left;
55+
}
56+
if (!memo.empty())
57+
{
58+
root = memo.top();
59+
memo.pop();
60+
61+
root = root->right;
62+
}
63+
}
64+
}
65+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp