Easy solution DFS


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int sumNumbers(TreeNode root) {
            
            // Error checking
            if(root == null) return 0;
            
            TreeNode result = new TreeNode(0);
            StringBuilder sb = new StringBuilder(root.val+"");
            
            dfs(root, result, sb);
            
            return result.val;
        }
        
        
        public void dfs(TreeNode node, TreeNode result, StringBuilder sb){
            
            
            if(node.left==null && node.right==null){
                result.val = result.val + Integer.parseInt(sb.toString());
            }
            
            if(node.left!=null){
                dfs(node.left, result, new StringBuilder(sb.toString()+node.left.val));
            }
            if(node.right!=null){
                dfs(node.right, result, new StringBuilder(sb.toString()+node.right.val));
            }
    
        }
        
    }

Log in to reply
 

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