๐ก 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.