/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        if(root == null){
            return 0;
        }
        Stack<TreeNode> nodeStack = new Stack<>();
        Stack<Integer> valueStack = new Stack<>();
        int result = 0;
        nodeStack.add(root);
        valueStack.add(root.val);
        while(!nodeStack.isEmpty()){
            TreeNode node = nodeStack.pop();
            int value = valueStack.pop();
            if(node.left == null && node.right == null){
                result += value;
            }else{
                if(node.right != null){
                    nodeStack.push(node.right);
                    valueStack.push(value *10 + node.right.val);
                }
                if(node.left != null){
                    nodeStack.push(node.left);
                    valueStack.push(value *10 +node.left.val);
                }
            }
 
            
        }
        return result;
    }
}