0814. 二叉树剪枝【中等】
1. 📝 题目描述
给你二叉树的根结点 root,此外树的每个结点的值要么是 0,要么是 1。
返回移除了所有不包含 1 的子树的原二叉树。
节点 node 的子树为 node 本身加上所有 node 的后代。
示例 1:

txt
输入:root = [1,null,0,0,1]
输出:[1,null,0,null,1]
解释:
只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。1
2
3
4
2
3
4
示例 2:

txt
输入:root = [1,0,1,0,0,0,1]
输出:[1,null,1,null,1]1
2
2
示例 3:

txt
输入:root = [1,1,0,1,1,0,1,0]
输出:[1,1,0,1,1,null,1]1
2
2
提示:
- 树中节点的数目在范围
[1, 200]内 Node.val为0或1
2. 🎯 s.1 - DFS
c
struct TreeNode* pruneTree(struct TreeNode* root) {
if (!root) return NULL;
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
if (root->val == 0 && !root->left && !root->right) return NULL;
return root;
}1
2
3
4
5
6
7
2
3
4
5
6
7
js
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var pruneTree = function (root) {
if (!root) return null
root.left = pruneTree(root.left)
root.right = pruneTree(root.right)
if (root.val === 0 && !root.left && !root.right) return null
return root
}1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
py
class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.val == 0 and not root.left and not root.right:
return None
return root1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 时间复杂度:
,其中 n 是节点数 - 空间复杂度:
,递归栈深度
算法思路:
- 后序遍历,先递归处理左右子树
- 若当前节点值为 0 且无子节点,则剪掉该节点