129. 求根到叶子节点数字之和

た 入场券 2022-12-23 07:10 317阅读 0赞

题目来源

129. 求根到叶子节点数字之和

题目描述

在这里插入图片描述

题目解析

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

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,317人围观)

还没有评论,来说两句吧...

相关阅读