Question about binary tree min and height

Hello everyone,

I have been following the data structure course and I notice in lesson 12(find tree min) the base case

`if(root.leftNode == null && root.rightNode == null)
    return root.value;

does not stop the recursion from attempting to read a null pointer in root.value

 private int min(Node root){
      //  if(root == null)
      //       will get a nullpointer exception without this base case?

        if(root.leftNode == null && root.rightNode == null)
           return root.value;

            int left =  min(root.leftNode);
            int right =  min(root.rightNode);

            return Math.min(Math.min(left, right), root.value);

    }

What am I missing here?

1 Like

Is your tree’s root a null value? Did you add any values to the tree before running the function?

Hey Alex,

The tree contains values. My point is that the base case in the course:

   if(root.leftNode == null && root.rightNode == null)
           return root.value;

Does not stop the program from trying to read from a null pointer unless the tree is completely synemtrical.

The base below worked for me:

 if(root == null)
  // a number greater than root.value;
     return Integer.MAX_VALUE;
1 Like

You mean like, when there’s a right child but no left child?
I’m going through the same course right now so sorry if I’m not so helpful :sweat_smile:

I remember also having trouble with Mosh’s base case. (IsLeaf() method)

Good to know your other base case works.

Hi, It looks like there is a bug. I realized it now on lesson 11. There we have the same base case which works just fine with the given example, but if we choose another tree that has no the same level order (left/right) we will get the same exception. It works fine with this new check you added.

In my case I did it in the same if condition.

if (root == null || root.LeftChild == null && root.RightChild == null)
            {
                return 0;
            }

Look good! you can omit the {} if you want :slight_smile:

Yes, I can. :slight_smile: In our company, we decided to use them always because in this way we will avoid bugs and actually, we have just few ifs with just one line of code inside.