解法一
递归计算子树的结点和,如果和为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) {
if (sumOfSubTree(root) == 0) {
return null;
} else {
return root;
}
}
private int sumOfSubTree(TreeNode root) {
if (root == null) {
return 0;
}
int sum = root.val;
int leftSum;
int rightSum;
if (root.left != null) {
leftSum = sumOfSubTree(root.left);
if (leftSum == 0) {
root.left = null;
}
sum += leftSum;
}
if (root.right != null) {
rightSum = sumOfSubTree(root.right);
if (rightSum == 0) {
root.right = null;
}
sum += rightSum;
}
if (sum == 0) {
root = null;
}
return sum;
}
}
解法二
评论区看到的解法,比我第一次自己写的简洁多了。不从求和角度入手来判断,递归完成后只需要考虑左右子结点和本身即可。
/**
* 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) {
if (root == null) {
return null;
}
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if ((root.left == null) && (root.right == null) && (root.val == 0)) {
root = null;
}
return root;
}
}