LeetCode之Leaf-Similar Trees(Kotlin)

问题:
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.


LeetCode之Leaf-Similar Trees(Kotlin)_第1张图片

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Note:
Both of the given trees will have between 1 and 100 nodes.


方法:
先遍历第一棵树的所有叶子节点,然后遍历第二棵树的所有叶子节点,然后比较两个叶子集合是否完全相同,如果完全相同则为相似树,如果不同则不是。

具体实现:

class LeafSimilarTrees {

    class TreeNode(var `val`: Int = 0) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

    fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean {
        val leftLeafs = getLeafs(root1)
        val rightLeafs = getLeafs(root2)
        if (leftLeafs.size != rightLeafs.size) {
            return false
        }
        for (index in leftLeafs.indices) {
            if (leftLeafs[index].`val` != rightLeafs[index].`val`) {
                return false
            }
        }
        return true
    }

    private fun getLeafs(root: TreeNode?): List {
        if (root == null) {
            return emptyList()
        }
        val result = mutableListOf()
        traverseLeafs(root, result)
        return result
    }

    private fun traverseLeafs(root: TreeNode?, result: MutableList) {
        if(root == null) {
            return
        }
        if (root.left != null) {
            traverseLeafs(root.left, result)
        }
        if (root.right != null) {
            traverseLeafs(root.right, result)
        }
        if (root.left == null && root.right == null) {
            result.add(root)
        }
    }
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Leaf-Similar Trees(Kotlin))