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. node

这里写图片描述


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

具体实现:github

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 实现测试用例
}
复制代码

有问题随时沟通bash

具体代码实现能够参考Github测试

相关文章
相关标签/搜索