LeetCode之Lowest Common Ancestor of Deepest Leaves(Kotlin)

問題: git


方法: 主要應用DFS進行遞歸遍歷,遍歷每一個節點的左右子樹,若是左右子樹的深度相同且爲最大深度或超過最大深度則返回該節點。github

具體實現:bash

var result: TreeNode? = null
    var maxDepth = 0

    fun lcaDeepestLeaves(root: TreeNode?): TreeNode? {
        dfs(root, 0)
        return result
    }

    private fun dfs(root: TreeNode?, depth: Int): Int {
        if (root == null) {
            return depth - 1
        }
        val left = dfs(root.left, depth + 1)
        val right = dfs(root.right, depth + 1)
        if (left == right && maxDepth <= left) {
            maxDepth = left
            result = root
        }
        return if (left > right) left else right
    }
}

fun main(args: Array<String>) {
    val one = LowestCommonAncestorOfDeepestLeaves.TreeNode(1)
    val two = LowestCommonAncestorOfDeepestLeaves.TreeNode(2)
    val three = LowestCommonAncestorOfDeepestLeaves.TreeNode(3)
    val four = LowestCommonAncestorOfDeepestLeaves.TreeNode(4)
    one.left = two
    one.right = three
    two.left = four
    val lowestCommonAncestorOfDeepestLeaves = LowestCommonAncestorOfDeepestLeaves()
    lowestCommonAncestorOfDeepestLeaves.lcaDeepestLeaves(one)
}
複製代碼

有問題隨時溝通ui

具體代碼實現能夠參考Githubspa

相關文章
相關標籤/搜索