一、题目内容

image.png

二、题解

解法1:

思路

先序遍历+求和
presum*10做移一位,加上根节点的val
判断左右节点都为空,则为叶子节点,返回结果;否则继续求和左右子树

代码

  1. import java.util.*;
  2. public class Solution {
  3. /**
  4. *
  5. * @param root TreeNode类
  6. * @return int整型
  7. */
  8. public int sumNumbers (TreeNode root) {
  9. // write code here
  10. if (root == null){
  11. return 0;
  12. }
  13. return recur(root, 0);
  14. }
  15. //先序遍历+求和
  16. public int recur(TreeNode root, int preSum){
  17. if(root == null){
  18. return 0;
  19. }
  20. int sum = preSum*10 + root.val;
  21. //root为叶子节点
  22. if(root.left == null && root.right == null){
  23. return sum;
  24. } else{
  25. return recur(root.left, sum) + recur(root.right, sum);
  26. }
  27. }
  28. }