-
Notifications
You must be signed in to change notification settings - Fork 0
/
same-tree.cpp
53 lines (48 loc) · 1.26 KB
/
same-tree.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
51
52
53
/**
* 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 isSameTree(TreeNode* p, TreeNode* q) {
if(!p && !q){
return true;
}
if((p && !q) || (!p && q)){
return false;
}
if( !p->left && !p->right && !q->left && !q->right){
if(p->val == q->val){
return true;
}
else{
return false;
}
}
if(p && q ){
if(p->val != q->val){
return false;
}
bool left_child = false;
if(!p->left && !q->left){
left_child = true;
}
if(p->left && q->left){
left_child = isSameTree(p->left, q->left);
}
bool right_child = false;
if(!p->right && !q->right){
right_child = true;
}
if(p->right && q->right){
right_child = isSameTree(p->right, q->right);
}
return left_child && right_child;
}
}
};