LeetCode 814. Binary Tree Pruning
2020-05-22 12:36:33 # leetcode

Problem

LeetCode 814. Binary Tree Pruning

1. 题目简述

给出一颗二叉树,其每个节点都由0或1组成,删除其所有的节点都为0的子树,返回新的树的root节点。例如:

Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]

Example

2. 算法思路

递归:

和以前的一些求子树和的题目很像,例如LeetCode 508. Most Frequent Subtree Sum,我们也可以求子树和,如果和为0,则说明将当前节点置为null即可。与返回布尔值的效果一致。仍然使用后序遍历。

3. 解法

  1. 如果节点为null,直接返回0.
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
int rootSum = subtreeSum(root);
if (rootSum == 0) {
return null;
}

return root;
}

private int subtreeSum(TreeNode root){
if (root == null) {
return 0;
}

int leftSum = subtreeSum(root.left);
int rightSum = subtreeSum(root.right);

if (leftSum == 0) {
root.left = null;
}
if (rightSum == 0) {
root.right = null;
}

return root.val + leftSum + rightSum;
}
}