Short and Neat solution in Java by DFS


  • 0
    Y
    public class Solution {
        int sum=0;
        public int sumNumbers(TreeNode root) {
            if(root==null) return 0;
            String str=""+root.val;
            DFS(root,str);
            return sum;
            
        }
        public void DFS(TreeNode root,String str){
            if(root.left!=null) DFS(root.left,str+root.left.val);
            if(root.right!=null) DFS(root.right,str+root.right.val);
            if(root.left==null&&root.right==null) sum=sum+Integer.parseInt(str);
        }
    }

Log in to reply
 

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