原题网址(中):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;
}
}
本文详细介绍了LeetCode上的一道经典算法题——二叉树剪枝的解题思路及实现代码。通过递归方法,去除所有不包含1值的子树,使读者能够深入理解并掌握该算法的核心思想。

9881

被折叠的 条评论
为什么被折叠?



