英文原文
Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Example 1:
Input: root = [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer.
Example 2:
Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1]
Example 3:
Input: root = [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1]
Constraints:
- The number of nodes in the tree is in the range
[1, 200]. Node.valis either0or1.
中文题目
给你二叉树的根结点 root ,此外树的每个结点的值要么是 0 ,要么是 1 。
返回移除了所有不包含 1 的子树的原二叉树。
节点 node 的子树为 node 本身加上所有 node 的后代。
示例 1:
输入:root = [1,null,0,0,1] 输出:[1,null,0,null,1] 解释: 只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。
示例 2:
输入:root = [1,0,1,0,0,0,1] 输出:[1,null,1,null,1]
示例 3:
输入:root = [1,1,0,1,1,0,1,0] 输出:[1,1,0,1,1,null,1]
提示:
- 树中节点的数目在范围
[1, 200]内 Node.val为0或1
通过代码
官方题解
递归:
我们可以使用递归来解决这个问题。我们用 containsOne(node) 函数来判断以 node 为根的子树中是否包含 1,其不包含 1 当且仅当以 node 的左右孩子为根的子树均不包含 1,并且 node 节点本身的值也不为 1。
如果 node 的左右孩子为根的子树不包含 1,那我们就需要把对应的指针置为空。例如当 node 的左孩子为根的子树不包含 1 时,我们将 node.left 置为 null。
在递归结束之后,如果整颗二叉树都不包含 1,那么我们返回 null,否则我们返回原来的根节点。
[sol1]class Solution { public TreeNode pruneTree(TreeNode root) { return containsOne(root) ? root : null; } public boolean containsOne(TreeNode node) { if (node == null) return false; boolean a1 = containsOne(node.left); boolean a2 = containsOne(node.right); if (!a1) node.left = null; if (!a2) node.right = null; return node.val == 1 || a1 || a2; } }
[sol1]class Solution(object): def pruneTree(self, root): def containsOne(node): if not node: return False a1 = containsOne(node.left) a2 = containsOne(node.right) if not a1: node.left = None if not a2: node.right = None return node.val == 1 or a1 or a2 return root if containsOne(root) else None
复杂度分析
时间复杂度:$O(N)$,其中 $N$ 是树中节点的个数。
空间复杂度:$O(H)$,其中 $H$ 是树的高度,为我们在递归时使用的栈空间大小。
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 24217 | 34600 | 70.0% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|