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]
2. 算法思路
递归:
和以前的一些求子树和的题目很像,例如LeetCode 508. Most Frequent Subtree Sum,我们也可以求子树和,如果和为0,则说明将当前节点置为null即可。与返回布尔值的效果一致。仍然使用后序遍历。
3. 解法
- 如果节点为null,直接返回0.
/**
* 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;
}
}
