[LeetCode] 872. Leaf-Similar Trees(Kotlin)

0

LeetCode

목록 보기
37/58
post-thumbnail

[LeetCode] 872. Leaf-Similar Trees(Kotlin)

풀이

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    private fun getLeafSeq(root:TreeNode?):MutableList<Int>{
        val leafSeq = mutableListOf<Int>()
        if(root == null) 
            return leafSeq
        if((root.left == null)&&(root.right == null)) 
            return (leafSeq + root.`val`).toMutableList()
        
        leafSeq.addAll(getLeafSeq(root.left))
        leafSeq.addAll(getLeafSeq(root.right))
        return leafSeq
    }

    fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean {
        val leafSeq1 = getLeafSeq(root1)
        val leafSeq2 = getLeafSeq(root2)
        return leafSeq1 == leafSeq2
    }
}
profile
Be able to be vulnerable, in search of truth

0개의 댓글