Post

šŸ’” 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.