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

相关文章
相关标签/搜索