노드순회하면서 리프면 배열에 추가후 비교
재귀사용
정답
class Solution {
fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean {
return leftFirstTreeLeafSearch(root1)==leftFirstTreeLeafSearch(root2)
}
fun leftFirstTreeLeafSearch(root1: TreeNode?):List<Int>{
val tempList = mutableListOf<Int>()
if (root1==null){
throw IllegalArgumentException()
}
if (root1.left==null && root1.right==null){
tempList.add(root1.`val`)
}
if(root1.left!=null){
tempList.addAll( leftFirstTreeLeafSearch(root1.left))
}
if(root1.right!=null){
tempList.addAll( leftFirstTreeLeafSearch(root1.right))
}
return tempList
}
}
'알고리즘' 카테고리의 다른 글
릿코드 1704. Determine if String Halves Are Alike 코틀린 (0) | 2024.01.12 |
---|---|
릿코드 1026. Maximum Difference Between Node and Ancestor 코틀린 (0) | 2024.01.11 |
릿코드 938. Range Sum of BST 코틀린 (0) | 2024.01.08 |
릿코드 300. Longest Increasing Subsequence 코틀린 (0) | 2024.01.05 |
릿코드 2870. Minimum Number of Operations to Make Array Empty 코틀린 (0) | 2024.01.04 |