Simple Java Solution


  • 0
    Z
     
    public class Solution {
        private int total;
    
        public int sumNumbers(TreeNode root) {
            traverse(root, "");
            return total;
        }
    
        public void traverse(TreeNode root, String sum) {
            if (root == null) {
                return;
            }
    
            if (root.left == null && root.right == null) {
                total += Integer.parseInt(sum + root.val);
            }
    
            traverse(root.left, sum + root.val);
            traverse(root.right, sum + root.val);
        }
    
    }
    

Log in to reply
 

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