由于其输入的性质,这种遍历树有些不同,也许这个图形表示会带来更多的清晰度:
输入:
5 # no of nodes
# key left-child right-child
4 1 2 # key 4 has left-child as key 2(index 1) and right-child as key 5(index 2)
2 3 4
5 -1 -1 # key 5 has no children thus both sides are assigned -1
1 -1 -1
3 -1 -1
输出树看起来像:
当前的任务是创建一棵树并输出节点的有序,前序和后序遍历
问题:许多测试用例都通过且没有失败,但是很少有测试用例输出一条消息:未知信号11 ,它也没有超出内存限制作为我检查过的那些测试用例的时限,未知信号11 到底是什么,为什么会出现?
我尝试过的方法:许多在线论坛建议增加堆栈的大小,但仍然显示相同的消息。
我想要什么:关于我应该在哪里修改代码以及为什么修改的任何建议?
我的代码:
import sys, threading
sys.setrecursionlimit(10**9) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size(i increased it upto size 31)
def preord(root, adic):
if root != -1:
k = adic[root]
print(k[0],end = ' ')
preord(k[1], adic)
preord(k[2], adic)
def postord(root, adic):
if root != -1:
k = adic[root]
postord(k[1], adic)
postord(k[2], adic)
print(k[0],end = ' ')
def inord(root, adic):
if root != -1:
k = adic[root]
inord(k[1], adic)
print(k[0],end = ' ')
inord(k[2], adic)
if __name__ == '__main__':
n = int(input())# no of nodes
adic = []
for _ in range(n):
ro, l, r = map(int, input().split())# accepts key and it's children
adic.append([ro, l, r])
inord(0, adic)
print()
preord(0, adic)
print()
postord(0, adic)