[英]Why is inorder tree traversal without recursion in Python running infinitely?
我正在嘗試在不使用遞歸的情況下對二叉樹進行中序樹遍歷,但似乎 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 is not None
不一樣
s!=[]
您的 s 是一個始終存在的堆棧,您實際上想檢查您的堆棧是否為空。
您總是將s
初始化為一個空列表,該列表永遠不會為None
。 您想檢查是否為not s
,而not s
是否s is not None
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.