-
Notifications
You must be signed in to change notification settings - Fork 0
/
SameTree.cpp
50 lines (43 loc) · 1.15 KB
/
SameTree.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
41
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
using namespace std;
/**
* 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 {
public:
vector<int> dfs(TreeNode* t) {
vector<int> preorder;
if (t == nullptr) {
return preorder;
}
preorder.reserve(101);
stack<TreeNode*> stack;
stack.push(t);
while (!stack.empty()) {
TreeNode* ele = stack.top();
stack.pop();
if (ele == nullptr) {
preorder.push_back(99999);
} else {
preorder.push_back(ele->val);
stack.push(ele->right);
stack.push(ele->left);
}
}
return preorder;
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if (dfs(p) == dfs(q)) {
return true;
}
return false;
}
};