問題: 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 實現測試用例
}
複製程式碼
有問題隨時溝通