【LeetCode】二叉树剪枝搜索(Binary Tree Pruning)

原题网址(中):https://leetcode-cn.com/problems/binary-tree-pruning/
原题网址(英):https://leetcode.com/problems/binary-tree-pruning/

题目:

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.).

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

示例:

输入: [1,null,0,0,1]
输出: [1,null,0,null,1]
在这里插入图片描述

思路:

简单的递归思想。

代码:
public class Prob814_binary_tree_pruning {

  public TreeNode pruneTree(TreeNode root) {
    if(root.left != null)
      root.left = pruneTree(root.left);
    if(root.right != null)
      root.right = pruneTree(root.right);
    if(root.left == null && root.right == null && root.val == 0)
      return null;
    return root;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值