Why was I wrong. Quick Question


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        int max = 0;
        
        public void getMax(TreeNode root, int count){
            if(count > max){
                max = count;
            }
            if(root.left != null){
                count++;
                getMax(root.left, count);
            } 
            if(root.right != null){
                count++;
                getMax(root.right, count);
            }
            if(root.left == null && root.right == null){
                return;
            }
        }
        
        public int maxDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            getMax(root, 1);
            return max;
        }
    }
    

    Whats wrong with this solution as oppose to this one.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        int max = 0;
        
        public void getMax(TreeNode root, int count){
            if(count > max){
                max = count;
            }
            if(root.left != null){
                getMax(root.left, count + 1);
            } 
            if(root.right != null){
                getMax(root.right, count + 1);
            }
            if(root.left == null && root.right == null){
                return;
            }
        }
        
        public int maxDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            getMax(root, 1);
            return max;
        }
    }
    

    The first one fails and the second one passes. Also, I know i'm not suppose to use globals and I can use Math.max. Just want to know the difference between incrementing count and just passing in the next number.
    Thanks guys.


  • 0
    G

    when you do count +1, you are not really adding 1 to count. You are just passing count +1, to the method. If you want to test this. print the value to count just before and after calling method. In wrong case. It will be same. In increment case, The value will differ by 1.


Log in to reply
 

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