Very clear java code and easy to understand


  • 0
    X
    public class Solution {
        private int totalSum = 0;
        private int subSum = 0;
    
        public int sumNumbers(TreeNode root) {
            if (root == null)
        	    return 0;
    	
            this.sumNumbersCore(root);
        
    	    return this.totalSum;
        }
    
        private void sumNumbersCore(TreeNode root) {
            this.subSum = this.subSum * 10 + root.val;
        
    	    if (root.left == null && root.right == null) 
        		    this.totalSum += this.subSum;
    	
    	    if (root.left != null) 
    		    sumNumbersCore(root.left);
    	
    	    if (root.right != null) 
    		    sumNumbersCore(root.right);
    	
    	    this.subSum = (this.subSum - root.val) / 10;
        }
    }

Log in to reply
 

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