美文网首页
LeetCode之Delete Leaves With a Gi

LeetCode之Delete Leaves With a Gi

作者: 糕冷羊 | 来源:发表于2020-11-22 15:26 被阅读0次

问题:



方法:
基于树的递归,但是需要回溯当前结点,最后一直回溯到根节点,如果当前结点是叶子结点同时等于target时回溯时返回null否则返回当前结点,最后就能得到正确的结果。

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

    fun removeLeafNodes(root: TreeNode?, target: Int): TreeNode? {
        if (root == null) {
            return root
        }
        return dfs(root, target)
    }

    private fun dfs(root: TreeNode, target: Int): TreeNode? {
        root.left = root.left?.let { dfs(it, target) }
        root.right = root.right?.let { dfs(it, target) }
        if (root.left == null && root.right == null && root.`val` == target) {
            return null
        }
        return root
    }
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Delete Leaves With a Gi

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