Python implementation of complete binary tree hierarchy traversal

7-11 Level sequence traversal of a complete binary tree (25 points)
A binary tree, if the number of nodes in each layer reaches the maximum, then the binary tree is a perfect binary tree. For a binary tree with a depth of D and N nodes, if its nodes correspond to the first N nodes of the sequence traversal of a perfect binary tree of the same depth, such a tree is a complete binary tree.
Given a post-order traversal of a complete binary tree, please give the result of the tree's traversal.
Input format: Input a positive integer N (≤30) in the first line, which is the number of nodes in the tree. The second line gives the post-order traversal sequence, which is N positive integers not exceeding 100. All numbers in the same line are separated by spaces.
Output format: output the traversal sequence of the tree in one line. All numbers are separated by 1 space, and there must be no extra spaces at the beginning and end of the line.

Sequence traversal: bfs/wide search top-down
post-order traversal: deep search bottom-up
middle-order traversal

Python code implementation:

def dfs(x): #后序建树
    global r #指向全局变量
    if x>n:
        return
    dfs(x*2)
    dfs(x*2+1)
    tree[x] = arr[r]
    r+=1
n,arr,tree,r=int(input()),[],{
    
    },0
arr=input().split()
dfs(1)

#层次遍历

for i in range(n):
    print(tree[i+1],end="")
    if i!=n-1:
        print(" ",end="")

Guess you like

Origin blog.csdn.net/weixin_56336619/article/details/115033402