๋ฌธ์
Given two binary trees, 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.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
dfs๋ก tree๋ฅผ ์ํํ๋ฉด ์ํ ์์๊ฐ ๊ฐ์๋ ๋๊ฐ์ง ๊ฒฝ์ฐ์ผ ๋ tree์ ๋ชจ์์ด ๋ฌ๋ผ์ง ์ ์๋ค.
- ์ผ์ชฝ leaf ์ธ์ง ์ค๋ฅธ์ชฝ leaf ์ธ์ง (example2)
- leaf ๋ฐฉํฅ์ ๊ฐ์๋ฐ depth ๊ฐ ๋ค๋ฅธ์ง ([10,5,15] [10,5,null,null,15])
dfs ๋ก traverse ํ๋ฉด์ leaf side ์ depth ๋ฅผ ์ ์ฅํ ์ ์๋ ํํ์ ๋ง๋ค์ด ๋ฐฐ์ด์ ์ ์ฅํ๋ค.
๋ง์ง๋ง์ผ๋ก ๋ฐฐ์ด์ ์ํํ๋ฉฐ ํํ ์์์ค ๋ค๋ฅธ๊ฒ ์์ผ๋ฉด return false ํ๋ค.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
var arr1 : [(Int,Int,Int)] = []
var arr2 : [(Int,Int,Int)] = []
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
if p == nil && q == nil {
return true
}else if p == nil && q != nil {
return false
}else if p != nil && q == nil {
return false
}
dfs(p!,0,0,0)
dfs(q!,0,1,0)
for i in 0..<arr1.count{
if (arr1[i].0 == arr2[i].0 && arr1[i].1 == arr2[i].1 && arr1[i].2 == arr2[i].2) == false {
return false
}
}
return true
}
func dfs(_ tree : TreeNode, _ side : Int, _ treeKind : Int, _ depth : Int){
//p: 0 q: 1
//center: 0, left: 1 right: 2
if treeKind == 0 {arr1.append((tree.val,side,depth))}
if treeKind == 1 {arr2.append((tree.val,side,depth))}
if tree.left != nil {
dfs(tree.left!,1,treeKind,depth+1)
}
if tree.right != nil {
dfs(tree.right!,2,treeKind,depth+1)
}
}
}
์ข์ ํด๋ต์ ์๋๊ฒ ๊ฐ์๊ฒ ๋๊ฐ์ tree๋ฅผ ๋์์ ํ๋์ฉ ์ํํ๋ฉฐ ๋ค๋ฅธ ๋ถ๋ถ์ด ๋์ค๋ ์ฆ์ return false ๋ฅผ ํ๋ฉด ์ข์ ๊ฒ ๊ฐ์๋ฐ ๋ด ์ฝ๋๋ ํธ๋ฆฌ์ ๊ตฌ์กฐ๊ฐ ๊ฐ๋ ๋ค๋ฅด๋ ๋ฌด์กฐ๊ฑด tree size *2 ๋ฒ์ traverse ํด์ผ ํ๋ค. (tree ์์ฒด + ๋ฐฉ๋ฌธ๋ฐฐ์ด).
์ข๋ ์๊ฐํด ๋ด์ผ๊ฒ ๋ค.
'Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฏ Daily LeetCode Challenge Day_14 - Angle between hands of a clock (0) | 2020.07.14 |
---|---|
LeetCode - Container With Most Water (0) | 2020.07.14 |
๐ฏ Daily LeetCode Challenge Day_12 - Reverse Bits (0) | 2020.07.12 |
๐ฏ Daily LeetCode Challenge Day_11 - Subsets (0) | 2020.07.12 |
๐ฏ Daily LeetCode Challenge Day_10 - Flatten a Multilevel Doubly Linked List (0) | 2020.07.10 |
๋๊ธ