简体   繁体   English

为什么在Python中无限运行无递归的中序树遍历?

[英]Why is inorder tree traversal without recursion in Python running infinitely?

I'm trying to do Inorder tree traversal for binary trees without using recursion but it seems like the while loop keeps running infinitely.我正在尝试在不使用递归的情况下对二叉树进行中序树遍历,但似乎 while 循环一直在无限运行。 Any help would be appreciated.任何帮助,将不胜感激。

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data


def inOrder(root):
    s = []
    while s is not None or root is not None:
        if root is not None:
            s.append(root.left)
            if root.left:
                root = root.left
        else:
            root = s.pop()
            print(root.data)
            if root.right:
                root = root.right


if __name__=='__main__':

    root = Node(5)
    root.left = Node(3)
    root.left.right = Node(2)
    root.left.left = Node(4)
    root.right = Node(10)
    root.right.left = Node(9)
    root.right.right = Node(20)

#            5 
#          /   \ 
#         3     10 
#       /  \   /  \
#      4    2 9    20

    inOrder(root)

Check the following code for inorder traversal: 检查以下代码以进行有序遍历:

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data


def inOrder(root):
    s = []
    s.append(root)
    while len(s) > 0: # Check if stack is not empty
        if root.left: #Case 1: Traverse left if there is an element left of the current root
            s.append(root.left)
            root = root.left
        else:
            root = s.pop() #Case 2: If there is no element on the left, print the current root
            print(root.data)
            if root.right: #Case 3: If there is an element on the right, traverse right of the current root
                s.append(root.right)
                root = root.right


if __name__=='__main__':

    root = Node(5)
    root.left = Node(3)
    root.left.right = Node(2)
    root.left.left = Node(4)
    root.right = Node(10)
    root.right.left = Node(9)
    root.right.right = Node(20)
    inOrder(root)

Your idea is correct but the problem is that你的想法是正确的,但问题是

s is not None

Is not the same as不一样

s!=[]

Your s is a stack which is always there and you actually want to check whether your stack is empty or not.您的 s 是一个始终存在的堆栈,您实际上想检查您的堆栈是否为空。

You are always initiating s to an empty list, which will never be None . 您总是将s初始化为一个空列表,该列表永远不会为None You wanted to check whether not s , not whether s is not None . 您想检查是否为not s ,而not s是否s is not None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM