[Leetcode]-- Sum Root to Leaf Numbers

 

 

[Leetcode]-- Sum Root to Leaf Numbers
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null) return 0;
        dfs(result, 0, root);
        int sum = 0;
        for(int i : result){
            sum += i;
        }
        
        return sum;
    }
    
    private void dfs(ArrayList<Integer> result, int now, TreeNode root){
        if(root.left == null && root.right == null){
            result.add(10*now+root.val);
        }
        
        now = now*10+root.val;;
        
        if(root.left != null){
            dfs(result, now, root.left);
        }
        if(root.right != null){
            dfs(result, now, root.right);
        }
    }
}
[Leetcode]-- Sum Root to Leaf Numbers

[Leetcode]-- Sum Root to Leaf Numbers

上一篇:Obj-C的hello,world 1


下一篇:[Leetcode]-- Binary Tree Level Order Traversal