Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情
题目
请根据二叉树的前序遍历,中序遍历恢复二叉树,并打印出二叉树的右视图
思路
这题我们可以先把这颗树构建出来,然后我们就可以再将进行层次遍历,就可以将这个最右边进行保存再进行输出即可。
AC Code
package main
func solve( xianxu []int , zhongxu []int ) []int {
// write code here
root := buildTree(xianxu, zhongxu)
queue := []*TreeNode{root}
res := []int{}
for len(queue) > 0 {
n := len(queue)
for i:=0;i<n;i++{
root = queue[0]
queue = queue[1:]
if root.Left!=nil{
queue = append(queue,root.Left)
}
if root.Right!=nil{
queue = append(queue, root.Right)
}
if i==n-1{
res = append(res, root.Val)
}
}
}
return res
}
以上代码就是将这棵树用bfs,用队列去存储树的节点信息,然后我们可以通过这个不断一层一层的遍历,当这个i已经到了每一层的最后一个的时候,就可以将这个最后的这个值保存到数组里面了。
func buildTree(preorder []int,inorder []int)*TreeNode{
if len(preorder)==0 || len(inorder)==0{
return nil
}
(1) root := &TreeNode{preorder[0],nil,nil}
i:=0
(2) for i=0;i<len(inorder);i++{
(3) if inorder[i]==preorder[0]{
(4) break
}
}
(5) root.Left = buildTree(preorder[1:len(inorder[:i])+1],inorder[:i])
// 中序[i]的左边
(6) root.Right = buildTree(preorder[len(inorder[:i])+1:],inorder[i+1:])
// 中序[i]的右边
(7) return root
}
- (1) 关键头节点,头节点就是先序遍历的第一个
- (2) 然后就进行循环遍历这个中序列表
- (3) 这个点就是中序的分割线,也就是分开了左右子树
- (4) 找到下标后就可以退出了
- (5) 然后继续进行递归,左边进行先序的下标为1到下标,遍历到哪里就要看中序的左边有多少了,然后中序列表就是左边一直到中间i的值,就是左边的范围
- (6) 右边就是与(5)相反的即可
- (7) 返回这个构建好的root树