Skip to content
本页目录

0814-二叉树剪枝

题目描述

https://leetcode.cn/problems/binary-tree-pruning

给你二叉树的根结点 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

思路

递归左右节点分别进行剪枝,当左节点都是0的时候,返回 null, 右节点同样处理。 然后本节点根据左右节点的返回值同样处理,当左右节点都为null,且自己是 0 的时候,返回null。

csharp
public class Solution {
    public TreeNode PruneTree(TreeNode root) {
        if(root == null){
            return null;
        }
        root.left = PruneTree(root.left);
        root.right = PruneTree(root.right);
        if(root.left == null && root.right == null && root.val == 0){
            return null;
        }
        else{
            return root;
        }
    }
}

Released under the MIT License.