Simple recursive solution by igcramos


  • 0
    I

    Based on Deep-search-first algorithm, using a recursive approach.

    Java

    class Solution {
        public int sumNumbers(TreeNode root) {
            int ret = 0;
                    
            if (root != null) {
                if (root.left != null) {
                    root.left.val = (root.val * 10) + root.left.val;
                    
                    ret = this.sumNumbers(root.left);
                }
                if (root.right != null) {
                    root.right.val = (root.val * 10) + root.right.val;
                    
                    ret += this.sumNumbers(root.right);
                }
            }
            return ret == 0 && root != null ? root.val : ret;
        }
    }
    
    

Log in to reply
 

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