美文网首页
LeetCode之Lowest Common Ancestor

LeetCode之Lowest Common Ancestor

作者: 糕冷羊 | 来源:发表于2019-08-12 15:27 被阅读0次

问题:



方法:
主要应用DFS进行递归遍历,遍历每个节点的左右子树,如果左右子树的深度相同且为最大深度或超过最大深度则返回该节点。

具体实现:

    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)
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Lowest Common Ancestor

      本文链接:https://www.haomeiwen.com/subject/fksujctx.html