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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sup_chao/article/details/84885636

原题网址(中):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;
  }
}

猜你喜欢

转载自blog.csdn.net/sup_chao/article/details/84885636