LeetCode之Binary Tree Pruning(Kotlin)

问题:
We are given the head node root of a binary tree, where additionally every node’s value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
Example 1:
Input: [1,null,0,0,1]
Output: [1,null,0,null,1]
Explanation:
Only the red nodes satisfy the property “every subtree not containing a 1”.
The diagram on the right represents the answer.
这里写图片描述


方法:
二叉树优先使用递归。第一种情况:左子树与右子树都需要裁剪且当前节点值为0则向上递归需要裁剪;第二种情况:左子树与右子树都需要裁剪且当前节点值为1则裁剪左右子树停止递归需要裁剪;第三种情况:左子树与右子树不是都需要裁剪则裁剪应该裁剪的子树并停止递归需要裁剪。判断当前节点是否需要裁剪的条件是值为0或者当前节点为空。

具体实现:

class BinaryTreePruning {
    // Definition for a binary tree node.
    class TreeNode(var `val`: Int = 0) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

    fun pruneTree(root: TreeNode?): TreeNode? {
        prune(root)
        return root
    }

    private fun prune(root: TreeNode?): Boolean {
        if (root == null) {
            return true
        }
        val leftPrune = prune(root.left)
        val rightPrune = prune(root.right)
        if (leftPrune && rightPrune) {
            if (root.`val` == 0) {
                return true
            } else {
                root.left = null
                root.right = null
                return false
            }
        } else {
            if (leftPrune) {
                root.left = null
            }
            if (rightPrune) {
                root.right = null
            }
            return false
        }
    }
}

fun main(args: Array<String>) {
    //todo 实现测试用例
}

有问题随时沟通

具体代码实现可以参考Github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值