Python. I am trying to iteratively perform inorder Traversal of a tree, but I am going into an infinite loop

82 Views Asked by At

Below in the solution class, I have an implementation of an inorder traversal (left, root, right).

For some reason I am entering into an infinte loop and I wonder if it is becaue of the way python handels consecutive if if/else statements?

# class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = righ
    
    class Solution:
        def inorderTraversal(self, root: TreeNode) -> List[int]:
            out = []
            stack = []
            if root is None:
                return out
            else:
                stack.append(root)
                while stack != []:
                    temp = stack.pop()
                    if temp.right:
                        stack.append(temp.right)
                    if temp.left:
                        a = temp.left
                        stack.append(temp)
                        stack.append(a)
                    else:
                        out.append(temp.val)
                return out
                
0

There are 0 best solutions below