Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Python中无递归的有序树遍历会无限运行?_Python_Python 3.x_Binary Tree_Tree Traversal_Inorder - Fatal编程技术网

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

为什么Python中无递归的有序树遍历会无限运行?,python,python-3.x,binary-tree,tree-traversal,inorder,Python,Python 3.x,Binary Tree,Tree Traversal,Inorder,我试图在不使用递归的情况下对二叉树进行有序树遍历,但while循环似乎一直在无限地运行。任何帮助都将不胜感激 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:

我试图在不使用递归的情况下对二叉树进行有序树遍历,但while循环似乎一直在无限地运行。任何帮助都将不胜感激

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)

检查以下代码中的顺序遍历:

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)

您总是将
s
初始化为一个空列表,该列表永远不会是
None
。您想检查
是否不是s
,而不是
s是否不是None

不是解决方案,但是
s
将永远不会是
None
。我也没有附加初始根节点,另一个答案指出了这一点。必须选择它作为正确的一个。不过,非常感谢你的帮助。