Post

๐Ÿ’ก LeetCode 101 - Symmetric Tree

๐Ÿ’ก LeetCode 101 - Symmetric Tree

๋ฌธ์ œ

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

์ž…์ถœ๋ ฅ ์˜ˆ์ œ

โœ… ์˜ˆ์ œ 1

1
2
Input: root = [1,2,2,3,4,4,3]
Output: true

โœ… ์˜ˆ์ œ 2

1
2
Input: root = [1,2,2,null,3,null,3]
Output: false

์ œ์•ฝ์กฐ๊ฑด

  • The number of nodes in the tree is in the range [1, 1000].ย 
  • -100ย <=ย Node.valย <=ย 100

์ž‘์„ฑ ์ฝ”๋“œ

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
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *ย ย ย ย  int val;
 *ย ย ย ย  TreeNode left;
 *ย ย ย ย  TreeNode right;
 *ย ย ย ย  TreeNode() {}
 *ย ย ย ย  TreeNode(int val) { this.val = val; }
 *ย ย ย ย  TreeNode(int val, TreeNode left, TreeNode right) {
 *ย ย ย ย ย ย ย ย  this.val = val;
 *ย ย ย ย ย ย ย ย  this.left = left;
 *ย ย ย ย ย ย ย ย  this.right = right;
 *ย ย ย ย  }
 * }
 */
class Solution {
	public boolean isSymmetric(TreeNode root) {
		// 1. ๋นˆ ๋…ธ๋“œ๊ฐ€ ์ฃผ์–ด์กŒ๋‹ค๋ฉด ์ฐธ ์ฒ˜๋ฆฌ
		if (root == null) return true;
		
		// 2. ๋ฐ˜ํ™˜
		return dfs(root.left, root.right);
	}
	
	/**
	 * DFS
	 */
	public boolean dfs(TreeNode leftChildNode, TreeNode rightChildNode) {
		// 1. ์œ ํšจ์„ฑ ์ฒดํฌ
		if (leftChildNode == null && rightChildNode == null) return true;
		if (leftChildNode == null || rightChildNode == null) return false;
		if (leftChildNode.val != rightChildNode.val) return false;
		
		// 2. DFS ์ฒ˜๋ฆฌ
		return dfs(leftChildNode.left, rightChildNode.right) && dfs(leftChildNode.right, rightChildNode.left);
	}
}

ํšŒ๊ณ 

  • BFS์™€ DFS ๋ชจ๋‘ ์ ์šฉ ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ ์–ด๋–ค ๋ฐฉ๋ฒ•์ด ๋”์šฑ ์ ํ•ฉํ•œ ์ง€๋„ ์ฒดํฌํ•ด์•ผ๊ฒ ๋‹ค.
This post is licensed under CC BY 4.0 by the author.