0

I have a problem in my program. Code as follows:

def getHeight(self,root):
    #Write your code here
    if not root:
        return -1
    if root.left:
        i = self.getHeight(root.left) + 1
    if root.right:
        j = self.getHeight(root.right) + 1
    return max(i, j)

Raises the error:

Traceback (most recent call last):
File "solution.py", line 37, in 
 height=myTree.getHeight(root)
File "solution.py", line 23, in getHeight
 i = self.getHeight(root.left) + 1
File "solution.py", line 23, in getHeight
 i = self.getHeight(root.left) + 1
File "solution.py", line 27, in getHeight
 return max(i, j)
UnboundLocalError: local variable 'i' referenced before assignment

And if I add i, j = 0, 0, it will work well.

And following code:

if True:
    i = 1 + 1

The code work well without initialization. Could someone please explain the difference?

1
  • 1
    They are two different actions, one is write (i = 1 + 1) and another is read (return max(i, j)). Before reading a variable, you need to create it first. Commented Jan 2, 2018 at 6:47

3 Answers 3

1

When you write i, j = 0, 0, you are initializing both variables to 0.

When you write i = 1 + 1, you are initializing i to 2, and because this is inside an if True, that code is always executed. So, you don't need to write if True as it will have the same effect.

To be clear, you always need to initialize variables before you read them. Always. What I am saying is that both corrections of your code are indeed initializing those variables. That's why they work.

Sign up to request clarification or add additional context in comments.

Comments

0

The condition is always.

The variable needs to be defined to be used. If the conditions are false, the variable is not defined.

You could use ternary statements instead to mitigate the issue

def getHeight(self,root):
    if not root:
        return -1
    i = self.getHeight(root.left) + 1 if root.left else 0
    j = self.getHeight(root.right) + 1 if root.right else 0
    return max(i, j)

2 Comments

I want to make sure your mean is that the variable can't defined in the process of recursion .so it‘s failed,thus raise the error.Do you?
I don't understand your question. Recursion isn't the problem... Variable scope is. You can define variables in recursive methods, and you already are
0

I think you should initial the variable before you reference it. In you code, the max function take the i, j as the argument.Thus the i, j need to be initialize. The if statement can't ensure the initialization, so the compiler gives you errors.

if true : i = 1 + 1

This code just assign the i with the value 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.