LeetCode之Leaf-Similar Trees(Kotlin)

嘟囔發表於2019-03-10

問題: 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)
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<TreeNode> {
        if (root == null) {
            return emptyList()
        }
        val result = mutableListOf<TreeNode>()
        traverseLeafs(root, result)
        return result
    }

    private fun traverseLeafs(root: TreeNode?, result: MutableList<TreeNode>) {
        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

相關文章