给你二叉树的根结点
root
,此外树的每个结点的值要么是0
,要么是1
。返回移除了所有不包含
1
的子树的原二叉树。节点
node
的子树为node
本身加上所有node
的后代。输入:root = [1,null,0,0,1] 输出:[1,null,0,null,1] 解释: 只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
// 二叉树剪枝使用递归遍历
// 当左右节点都为空并且当前节点的值为0 的情况下,就可以剪掉
var pruneTree = function(root) {
if(!root){
return null;
}
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(!root.left && !root.right && root.val === 0){
return null;
}
return root;
};