129 Sum Root to Leaf Numbers

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了129 Sum Root to Leaf Numbers相关的知识,希望对你有一定的参考价值。

129 Sum Root to Leaf Numbers


https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/41363/Short-Java-solution.-Recursion.



不是自己写的, tree 的 recursion 做的 不好
class Solution {
    public int sumNumbers(TreeNode root) {
      return sum(root, 0);
    }
    private int sum(TreeNode n, int prev){
      if(n == null){
        return 0;
      }
      if(n.right == null && n.left == null){
        return prev * 10 + n.val;
      }
      int left = sum(n.left, prev * 10 + n.val);
      int right = sum(n.right, prev * 10 + n.val);
      int sum = left + right;
      return sum;
        
    }
}

 

以上是关于129 Sum Root to Leaf Numbers的主要内容,如果未能解决你的问题,请参考以下文章