问题:
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 实现测试用例
}
有问题随时沟通