Share my simple readable Java implementation


  • 0
    S

    I'm using a static variable sum. This is not ideal and we should avoid it absolutely. But in this case, it makes the solution truly straightforward.

    public class Solution {
        private static int sum=0;
        public int sumNumbers(TreeNode root) {
            if (root == null){
                return 0;
            }
            sum = 0;
            int temp =root.val;
            
            sumNumbers2(root, temp);
            return sum;
        }
        
        private void sumNumbers2(TreeNode cur, int temp){
            if(cur.left==null&&cur.right==null){
                sum += temp; //cur is a leaf, add the value to the sum
                return;
            }
            
            if(cur.left != null){
                sumNumbers2(cur.left, temp*10+cur.left.val);
            }
            
            if(cur.right != null){
                sumNumbers2(cur.right, temp*10+cur.right.val);
            }
        }
        
        
    }

  • 0
    R

    Hi sharon, I want to know why we should avoid static variable?
    I usually use instance variable rather than static variable in this case, it seems that instance variable should also be avoided? Could you please explain why?
    Thanks


  • 0
    S

    Here is a good post about why global (static) variable is bad. http://c2.com/cgi/wiki?GlobalVariablesAreBad

    To me, the main reason for avoiding static variable is that when the program become big, its very difficult to reason what does the static variable mean in the whole program's context.

    I think instance variable is fine in this case though.


  • 0
    C

    Yes I think we should avoid. Since Java only support pass by value, it's impossible to pass a simple variable by reference to keep track of the sum value, and static is the only option if we want to make the code very simple. But we should keep everything related to a function inside a function, thus avoiding static is a good practice.


  • 2
    C

    I came up with almost the same solution but without the use of a static variable.
    Instead of updating a static sum, I'm returning the value calculated so far.

    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
    
        return calculateSum(root, 0);
    }
    
    private int calculateSum(TreeNode root, int cv) {
        if (root.left == null && root.right == null) {
            return 10 * cv + root.val;
        }
    
        int level = 0;
    
        if (root.left != null) {
            level += calculateSum(root.left, 10 * cv + root.val);
        }
    
        if (root.right != null) {
            level += calculateSum(root.right, 10 * cv + root.val);
        }
    
        return level;
    }

  • 0
    S

    this is apparently the better solution! thanks


Log in to reply
 

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