Xin chào mọi người, em đang học python. Em bị gặp lỗi như tiêu đề, nhưng không biết tại sao sai hết, mọi người xem và chỉ giúp em, em xin cảm ơn nhiều.
Đây là bài duyệt cây cơ bản.
# python3
import sys, threading
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class TreeOrders:
def read(self):
self.n = int(sys.stdin.readline())
self.key = [0 for i in range(self.n)]
self.left = [0 for i in range(self.n)]
self.right = [0 for i in range(self.n)]
for i in range(self.n):
[a, b, c] = map(int, sys.stdin.readline().split())
self.key[i] = a
self.left[i] = b
self.right[i] = c
def inOrder_recur(self, result, i):
if self.left[i] != -1:
inOrder_recur(result, left[i])
result.append(self.key[i])
if self.right[i] != -1:
inOrder_recur(result, right[i])
def inOrder(self):
self.result = []
# Finish the implementation
# You may need to add a new recursive method to do that
inOrder_recur(self.result, 0)
return self.result
def preOrder_recur(self, result, i):
result.append(self.key[i])
if self.left[i] != -1:
preOrder_recur(result, self.left[i])
if self.right[i] != -1:
preOrder_recur(result, self.right[i])
def preOrder(self):
self.result = []
# Finish the implementation
# You may need to add a new recursive method to do that
preOrder_recur(self.result, 0)
return self.result
def postorder_recur(self, result, i):
if self.left[i] != -1:
postorder_recur(result, self.left[i])
if self.right[i] != -1:
postorder_recur(result, self.right[i])
result.append(self.key[i])
def postOrder(self):
self.result = []
# Finish the implementation
# You may need to add a new recursive method to do that
postorder_recur(self.result, 0)
return self.result
def main():
tree = TreeOrders()
tree.read()
print(" ".join(str(x) for x in tree.inOrder()))
print(" ".join(str(x) for x in tree.preOrder()))
print(" ".join(str(x) for x in tree.postOrder()))
threading.Thread(target=main).start()