File tree 1 file changed +81
-0
lines changed
1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Given two binary trees, write a function to check if they are the same or not.
3
+
4
+ Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
5
+
6
+ Example 1:
7
+
8
+ Input: 1 1
9
+ / \ / \
10
+ 2 3 2 3
11
+
12
+ [1,2,3], [1,2,3]
13
+
14
+ Output: true
15
+ Example 2:
16
+
17
+ Input: 1 1
18
+ / \
19
+ 2 2
20
+
21
+ [1,2], [1,null,2]
22
+
23
+ Output: false
24
+ Example 3:
25
+
26
+ Input: 1 1
27
+ / \ / \
28
+ 2 1 1 2
29
+
30
+ [1,2,1], [1,1,2]
31
+
32
+ Output: false
33
+
34
+ 来源:力扣(LeetCode)
35
+ 链接:https://leetcode-cn.com/problems/same-tree
36
+ 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
37
+ */
38
+
39
+ #include < stack>
40
+ using namespace std ;
41
+
42
+ struct TreeNode {
43
+ int val;
44
+ TreeNode *left;
45
+ TreeNode *right;
46
+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
47
+ };
48
+
49
+ class Solution {
50
+ public:
51
+ bool isSameTree (TreeNode* p, TreeNode* q) {
52
+ if ((NULL ==p)&&(NULL ==q)) return true ;
53
+ else if (NULL ==p) return false ;
54
+ else if (NULL ==q) return false ;
55
+ stack<TreeNode*> s_p;
56
+ stack<TreeNode*> s_q;
57
+
58
+ s_p.push (p);
59
+ s_q.push (q);
60
+ while (!s_p.empty ()){
61
+ TreeNode* tmp_p = s_p.top (); s_p.pop ();
62
+ TreeNode* tmp_q = s_q.top (); s_q.pop ();
63
+ // compare val
64
+ if (tmp_p->val !=tmp_q->val ) return false ;
65
+ // right
66
+ if ((NULL !=tmp_p->right )&&(NULL !=tmp_q->right )){
67
+ s_p.push (tmp_p->right );
68
+ s_q.push (tmp_q->right );
69
+ }
70
+ else if ((NULL !=tmp_p->right )||(NULL !=tmp_q->right )) return false ;
71
+ // left
72
+ if ((NULL !=tmp_p->left )&&(NULL !=tmp_q->left )){
73
+ s_p.push (tmp_p->left );
74
+ s_q.push (tmp_q->left );
75
+ }
76
+ else if ((NULL !=tmp_p->left )||(NULL !=tmp_q->left )) return false ;
77
+ }
78
+
79
+ return true ;
80
+ }
81
+ };
You can’t perform that action at this time.
0 commit comments