0

I am getting below error name i is not defined at line i += 1 I tried putting at class Solution level. Getting same error

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        i = 0
        def inOrder(root):
            global i
            if root == None:
                return
            inOrder(root.left)
            i += 1
            if i == k:
                return
            inOrder(root.right)

        inOrder(root)
        return i

2 Answers 2

1

There is no global i. The variable you want is in the non-local enclosing scope.

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        i = 0
        def inOrder(root):
            nonlocal i
            if root == None:
                return
            inOrder(root.left)
            i += 1
            if i == k:
                return
            inOrder(root.right)

        inOrder(root)
        return i
Sign up to request clarification or add additional context in comments.

Comments

0

The scopes of kthSmallest and inOrder are different. Without specifying i as a global variable in kthSmallest, i won't be known inside inOrder.

Nested functions scopes

For nested functions, you need to declare your global variable in the parent function scope as well.

    class Solution:

        def kthSmallest(self, root: TreeNode, k: int) -> int:
            global i
            i = 0

            def inOrder(root):
                global i
                if root is None:
                    return
                inOrder(root.left)
                i += 1
                if i == k:
                    return
                inOrder(root.right)

            inOrder(root)
            return i

Remark 1

It looks like you are using a class in your example. You could also have done the following:

    class Solution:
        self.i = 0
        def kthSmallest(self, root: TreeNode, k: int) -> int:
            self.i = 0 

            def inOrder(root):
                if root is None:
                    return
                inOrder(root.left)
                self.i += 1
                if self.i == k:
                    return
                inOrder(root.right)

            inOrder(root)
            return i

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.