Skip to content

Commit 78af547

Browse files
committed
🚀 14-Jul-2020
1 parent 02ecee8 commit 78af547

File tree

2 files changed

+121
-0
lines changed

2 files changed

+121
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
35+
36+
37+
38+
39+
40+
41+
42+
43+
/**
44+
* Definition for a binary tree node.
45+
* struct TreeNode {
46+
* int val;
47+
* TreeNode *left;
48+
* TreeNode *right;
49+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
50+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
51+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
52+
* };
53+
*/
54+
class Solution {
55+
public:
56+
bool isSameTree(TreeNode* p, TreeNode* q) {
57+
if(!p && !q) return true;
58+
else if(!p || !q || p->val!=q->val) return false;
59+
else return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
60+
}
61+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
Given two binary trees, write a function to check if they are the same or not.
2+
3+
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
4+
5+
Example 1:
6+
7+
Input: 1 1
8+
/ \ / \
9+
2 3 2 3
10+
11+
[1,2,3], [1,2,3]
12+
13+
Output: true
14+
Example 2:
15+
16+
Input: 1 1
17+
/ \
18+
2 2
19+
20+
[1,2], [1,null,2]
21+
22+
Output: false
23+
Example 3:
24+
25+
Input: 1 1
26+
/ \ / \
27+
2 1 1 2
28+
29+
[1,2,1], [1,1,2]
30+
31+
Output: false
32+
33+
34+
35+
36+
37+
38+
39+
40+
41+
42+
/**
43+
* Definition for a binary tree node.
44+
* struct TreeNode {
45+
* int val;
46+
* TreeNode *left;
47+
* TreeNode *right;
48+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
49+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
50+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
51+
* };
52+
*/
53+
class Solution {
54+
public:
55+
bool isSameTree(TreeNode* p, TreeNode* q) {
56+
if(!p && !q) return true;
57+
else if(!p || !q || p->val!=q->val) return false;
58+
else return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
59+
}
60+
};

0 commit comments

Comments
 (0)