华为0830-题解-频率搬移值分配| 二叉树构建+层序遍历
python
原题题目自行搜索
题解
思路:
dfs二叉树构建+层序遍历二叉树
- dfs深度搜优先递归每个节点的值,同时根据dfs带来的前序遍历效果==构建二叉树==
- 二叉树层序遍历
n = int(input()) leaves = list(map(int,input().split())) class Tree(): def __init__(self,val): self.left = None self.right = None self.val = val c= []#测试使用,用于打印 #深度优先搜索的过程,顺便构造二叉树 def dfs(left,right,sumroot): if left>right: return mid = (left+right)//2 avg = (min(leaves[left:right+1])+max(leaves[left:right+1]))//2 val = avg-sumroot c.append(val) node = Tree(val) if left==right: return Tree(val) node.left = dfs(left,mid,sumroot+val) node.right = dfs(mid+1,right,sumroot+val) return node # root即为构造好的二叉树 root = dfs(0,len(leaves)-1,0) #常规的二叉树层序遍历 from collections import deque stack = deque() stack.append(root) res = [] while stack: node = stack.popleft() res.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) #result print(' '.join([str(item) for item in res]))#offer等你##华为求职进展汇总##我的求职思考#