解法一

递归计算子树的结点和,如果和为0则进行剪枝。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public TreeNode pruneTree(TreeNode root) {
  18. if (sumOfSubTree(root) == 0) {
  19. return null;
  20. } else {
  21. return root;
  22. }
  23. }
  24. private int sumOfSubTree(TreeNode root) {
  25. if (root == null) {
  26. return 0;
  27. }
  28. int sum = root.val;
  29. int leftSum;
  30. int rightSum;
  31. if (root.left != null) {
  32. leftSum = sumOfSubTree(root.left);
  33. if (leftSum == 0) {
  34. root.left = null;
  35. }
  36. sum += leftSum;
  37. }
  38. if (root.right != null) {
  39. rightSum = sumOfSubTree(root.right);
  40. if (rightSum == 0) {
  41. root.right = null;
  42. }
  43. sum += rightSum;
  44. }
  45. if (sum == 0) {
  46. root = null;
  47. }
  48. return sum;
  49. }
  50. }

解法二

评论区看到的解法,比我第一次自己写的简洁多了。不从求和角度入手来判断,递归完成后只需要考虑左右子结点和本身即可。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public TreeNode pruneTree(TreeNode root) {
  18. if (root == null) {
  19. return null;
  20. }
  21. root.left = pruneTree(root.left);
  22. root.right = pruneTree(root.right);
  23. if ((root.left == null) && (root.right == null) && (root.val == 0)) {
  24. root = null;
  25. }
  26. return root;
  27. }
  28. }