my simple java DFS solution


  • 0
    E
    public class Solution {
        public int sumNumbers(TreeNode root) {
            if (root == null) {
                return 0;
            }
            List<Integer> result = new ArrayList<>();
            sum(root, result, 0);
            int ans = 0;
            for (Integer q : result) {
                ans += q;
            }
            return ans;
        }
        
        private void sum(TreeNode root, List<Integer> result, Integer sum) {
            if (root == null) {
                return;
            }
            if (root.left == null && root.right == null) {
                sum = sum * 10 + root.val;
                result.add(sum);
                return;
            }
            sum = sum * 10 + root.val;
            sum(root.left, result, sum);
            sum(root.right, result, sum);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.