二叉树按层从左至右与“之”字形打印

题目描述:从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
输入:
8 1
1 2 3
2 4 0
4 0 0
3 5 6
5 7 8
6 0 0
7 0 0
8 0 0
输出
Level 1 : 1
Level 2 : 2 3
Level 3 : 4 5 6
Level 4 : 7 8
Level 1 from left to right: 1
Level 2 from right to left: 3 2
Level 3 from left to right: 4 5 6
Level 4 from right to left: 8 7

代码:
def print_tree(num, root, nodes):
    res = [[root]]
    while(num > 1):
        temp = []
        for k in res[-1]:
            if k in nodes.keys():
                for j in nodes[k]:
                    if j != 0:
                        temp.append(j)
                        num -= 1
        if temp:
            res.append(temp)
    return res


nodes = {}
num, root = map(int, input().split(' '))
for i in range(num):
    k, v1, v2 = map(int, input().split(' '))
    nodes[k] = [v1, v2]
res = print_tree(num, root, nodes)
for i in range(0, len(res)):
    print('Level '+str(i+1)+' : ' + ' '.join([str(k) for k in res[i]]))
for i in range(0, len(res)):
    if i % 2 == 0:
        print('Level '+str(i+1)+' from left to right: ' + ' '.join([str(k) for k in res[i]]))
    else:
        print('Level '+str(i+1)+' from right to left: ' + ' '.join([str(k) for k in res[i][::-1]]))




全部评论

相关推荐

若怜君欢:驾驶证去掉吧,PPT啥的也去掉,本硕课程去掉,导师和研究方向去掉;加入本硕排名(好才写);技能栏加入你会的那些控制算法和滤波算法,这个比你会啥啥啥软件更有用;获奖写上去,奖学金啊,有没有专利啊之类的 电机和硬件这一块,属于传统制造业,制造业实习并不多。多投一些攒攒经验,有实习最好,没有也不需要焦虑(制造业实习其实除了转正,没多大用处) 最后,划重点,等秋招开始后,把你所有社交软件都发一份简历上去,并经常更新,找人内推你!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务