My accepted Java solution using 3ms


  • 0
    G
    public class Solution {
        public int sumNumbers(TreeNode root) {
            ArrayDeque<Integer> tmpSum = new ArrayDeque<Integer>();
            if(root==null)
            {
                return 0;
            }
            dfs(tmpSum,root,"");
            int result = 0;
            while(tmpSum.isEmpty()==false)
            {
                result+=tmpSum.pop();
            }
            return result;
        }
        public void dfs(ArrayDeque<Integer> tmpSum,TreeNode root,String str)
        {
            if(root==null)
            {
                return;
            }
            str+=root.val;
            if((root.left!=null)||(root.right!=null))
            {
                dfs(tmpSum,root.left,str);
                dfs(tmpSum,root.right,str);
            }
            else
                tmpSum.push(Integer.parseInt(str));
        }
    }
    

    Using DFS-recursion method to traverse the binary tree and add the values of nodes in a root-to-leaf path to a String, and then convert the String to Integer and store the Integer into a stack.
    When the recursion is over, using a while-circulation to pop the elements in the stack and sum them and get the result.


Log in to reply
 

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