š” LeetCode 100 - Same Tree
š” LeetCode 100 - Same Tree
문ģ
GivenĀ theĀ rootsĀ ofĀ twoĀ binaryĀ treesĀ pĀ andĀ q,Ā writeĀ aĀ functionĀ toĀ checkĀ ifĀ theyĀ areĀ theĀ sameĀ orĀ not. TwoĀ binaryĀ treesĀ areĀ consideredĀ theĀ sameĀ ifĀ theyĀ areĀ structurallyĀ identical,Ā andĀ theĀ nodesĀ haveĀ theĀ sameĀ value.
ģ ģ¶ė „ ģģ
ā ģģ 1
1
2
Input: p = [1,2,3], q = [1,2,3]
Output: true
ā ģģ 2
1
2
Input: p = [1,2], q = [1,null,2]
Output: false
ā ģģ 3
1
2
Input: p = [1,2,1], q = [1,1,2]
Output: false
ģ ģ½ģ”°ź±“
- The number of nodes in both trees is in the range [0, 100].Ā
-10^4 <= Node.val <= 10^4
ģģ± ģ½ė
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
import java.util.Stack;
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// 1. ė³ģ ģ ģø ė° ģ“źø°ķ
Stack<TreeNode> stackP = new Stack<>();
Stack<TreeNode> stackQ = new Stack<>();
// 2. ģ¤ģ ģķ
while ((p != null || !stackP.isEmpty()) && (q != null || !stackQ.isEmpty())) {
// ģ¼ģŖ½ ģģ ė
øėė” ģ“ė
while (p != null && q != null) {
stackP.push(p);
stackQ.push(q);
p = p.left;
q = q.left;
}
// ģ ķØģ± 첓ķ¬
if (p == null ^ q == null) return false;
// ė¶ėŖØ ė
øėė” ģ“ė
p = stackP.pop();
q = stackQ.pop();
// ģ ķØģ± 첓ķ¬
if (p.val != q.val) return false;
// ģ¤ė„øģŖ½ ģģ ė
øėė” ģ“ė
p = p.right;
q = q.right;
}
// 3. ė°ķ
return p == null && q == null;
}
}
ķź³
XOR
ģ°ģ°ģ ģ½ėģ ģ²ģ ģØė“¤ė¤.
1
if ((p != null && q != null) && (p == null || q == null)) return false;
- ź·øėģ 씰걓문ģ ģģ±ķ ė
AND
ģėė©“OR
ė§ ź³ ė ¤ķėė°, ģģ¼ė”ėXOR
ė ģ ģ©ķ ģ ģėģ§ ź³ ė ¤ķ“ģ¼ź² ė¤.
This post is licensed under CC BY 4.0 by the author.