-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSameTree.h
50 lines (48 loc) · 1.1 KB
/
SameTree.h
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
*Solution 1: iterative
*time:O(n) space:O(logn)
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
stack<TreeNode*> stk;
stk.push(p);
stk.push(q);
while(!stk.empty())
{
p=stk.top();stk.pop();
q=stk.top();stk.pop();
if(!p&&!q)continue;
if(!p||!q)return false;
if(p->val!=q->val)return false;
stk.push(p->left);
stk.push(q->left);
stk.push(p->right);
stk.push(q->right);
}
return true;
}
};
/**
*Solution 2: recursive
*time:O(n) space:O(logn)
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(!p&&!q)return true;
if(!p||!q)return false;
if(p->val!=q->val)return false;
if(!isSameTree(p->left,q->left)||!isSameTree(p->right,q->right))return false;
return true;
}
};