FB 面经 Delete subtree sum zero

static TreeNode delete(TreeNode root) { 
    if (root == null) {
      return null;
    }
    int sum = deleteSum(root);
    if (sum == 0) {
      return null;
    }
    return root;
  } 
  int deleteSum(TreeNode root) {
    if (root == null) {
      return 0;
    }
    int left = deleteSum(root.left);
    int right = deleteSum(root.right);
    if (left == 0) {
      root.left = null;
    }
    if (right == 0) {
      root.right = 0;
    }
    return root.val+left+right;
  }

你可能感兴趣的:(FB 面经 Delete subtree sum zero)