814 二叉树剪枝

题目描述:
给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。
返回移除了所有不包含 1 的子树的原二叉树。
( 节点 X 的子树为 X 本身,以及所有 X 的后代。)

示例1:
输入: [1,null,0,0,1]
输出: [1,null,0,null,1]

解释:
只有红色节点满足条件“所有不包含 1 的子树”。
右图为返回的答案。
在这里插入图片描述
示例2:
输入: [1,0,1,0,0,0,1]
输出: [1,null,1,null,1]
在这里插入图片描述
示例3:
输入: [1,1,0,1,1,0,1,0]
输出: [1,1,0,1,1,null,1]
在这里插入图片描述说明:
给定的二叉树最多有 100 个节点。
每个节点的值只会为 0 或 1 。

方法1:
主要思路:解题链接汇总
(1)使用后序遍历的思路;
(2)确定当前结点的左右子树中1的个数,若是左子树中1的个数为0,则去除该子树,若是右子树中1的个数为0,则去除右子树;
(3)返回当前结点作为子树根节点时,1的个数;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int helper(TreeNode* root){
        if(root==nullptr){
            return 0;
        }
        //获得左右子树中1的个数
        int left_one=helper(root->left);
        int right_one=helper(root->right);
        //判断是否删除左右子树
        if(left_one==0){
            root->left=nullptr;
        }
        if(right_one==0){
            root->right=nullptr;
        }
        //统计当前结点左右根节点的子树中1的个数
        int cur_one=left_one+right_one;
        if(root->val==1){
            cur_one++;
        }
        return cur_one;
    }
    TreeNode* pruneTree(TreeNode* root) {
        if(root==nullptr) {
            return root;
        }
        int all_one=helper(root);
        if(all_one==0){
            return nullptr;
        }
        return root;
    }
};

//go实现

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 func helper(root *TreeNode)int {
     if root==nil {
         return 0
     }
     left_one := helper(root.Left)
     right_one := helper(root.Right)
     if left_one==0 {
         root.Left=nil
     }
     if right_one==0 {
         root.Right=nil
     }
     cur_one := left_one+right_one
     if root.Val==1 {
         cur_one++
     }
     return cur_one
 }
func pruneTree(root *TreeNode) *TreeNode {
    all_one := helper(root)
    if all_one==0 {
        return nil
    }
    return root
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值