题目
给你二叉树的根结点 root ,此外树的每个结点的值要么是 0 ,要么是 1 。
返回移除了所有不包含 1 的子树的原二叉树。
节点 node 的子树为 node 本身加上所有 node 的后代。
示例 1:
输入:root = [1,null,0,0,1]
输出:[1,null,0,null,1]
解释:
只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。
示例 2:

输入:root = [1,0,1,0,0,0,1]
输出:[1,null,1,null,1]
示例 3:
输入:root = [1,1,0,1,1,0,1,0]
输出:[1,1,0,1,1,null,1]
提示:
树中节点的数目在范围 [1, 200] 内
Node.val 为 0 或 1
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 递归,遍历树,边遍历遍改变树的结构
public TreeNode pruneTree(TreeNode root) {
if( root == null){
return null;
}
// 判断该树的左右孩子是否为空,如果是不包含1的子树,也将其置为null
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.left == null && root.right == null && root.val == 0){
return null;
}
return root;
}
}
这是一个关于二叉树处理的问题,目标是移除所有不包含1的子树。给定一个二叉树,每个节点的值为0或1,我们需要在原地修改树的结构,将所有不包含1的子树替换为null。提供的解决方案使用了递归方法,通过遍历树并在遍历过程中检查并更新节点来实现这一目标。
370

被折叠的 条评论
为什么被折叠?



