「每日LeetCode」2022年7月21日

本文最后更新于:2023年3月19日 晚上

814.二叉树剪枝

814.二叉树剪枝

Category Difficulty Likes Dislikes
algorithms Medium (70.22%) 247 -

Tags
Companies
给你二叉树的根结点 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

Discussion | Solution

思路

按题意 dfs 遍历和判断是否有 1 即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @lc app=leetcode.cn id=814 lang=javascript
*
* [814] 二叉树剪枝
*/

// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var pruneTree = function (root) {
const find = (node) => {
if (!node) return false;
if (node.val === 1) return true;
return find(node.left) || find(node.right);
};

const visit = (node) => {
if (!node) return null;
if (!find(node)) {
node = null;
return null;
}
if (!find(node.left)) {
node.left = null;
}
if (!find(node.right)) {
node.right = null;
}

visit(node.left);
visit(node.right);

return node;
};

return visit(root);
};
// @lc code=end