【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;
}
}
————————————————
版权声明:本文为CSDN博主「mistical」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sup_chao/article/details/84885636

posted @ 2020-03-14 17:46  天涯海角路  阅读(102)  评论(0)    收藏  举报