已知二叉樹前序遍歷和中序遍歷的結果,重建二叉樹
解決思路:
- 前序遍歷的結果中根節點在左右孩子的前面,左孩子在右孩子前面;中序遍歷的結果中根節點在左右孩子的中間,中序遍歷可以找出根節點的左子樹和右子樹,前序遍歷的第一個節點是根節點,根據這些特性可以遞歸的重建二叉樹
例如 pre=[1,2,4,7,3,5,6,8] mid=[4,7,2,1,5,3,8,6]
-
1作為根節點,左子樹[4,7,2] 右子樹[5,3,8,6]
-
左子樹[4,7,2]中由於前序遍歷結果2在前面,所以2位左子樹根節點;同理3是右子樹根節點;因此2有左子樹[4,7]沒右子樹,3有左子樹5,右子樹[8,6]
-
[4,7]由於前序遍歷中4在前面,所以4是根節點,4右子樹為[7];同理[8,6]中6為根節點,[8]是左子樹
-
最終二叉樹為[1,2,3,4,null,5,6,null,7,null,null,null,null,8]
1 2 3 4 5 6 7 8
- 采用排序二叉樹中序遍歷為有序數組的特性
1.思路一
func main() {
pre := []int{1, 2, 4, 7, 3, 5, 6, 8} // 根節點
mid := []int{4, 7, 2, 1, 5, 3, 8, 6}
root := new(node)
reBuildTree(root, pre, mid)
// 前序遍歷
preV(root)
fmt.Println()
// 中序遍歷
midV(root)
fmt.Println()
}
// 重建左子樹
func reBuildTree(root *node, pre, mid []int) {
if len(pre) == 0 {
return
}
// 確定根節點
root.val = pre[0]
var idx int
for ; mid[idx] != pre[0]; idx++ {
}
//左子樹
leftMid := mid[:idx]
leftPre := pre[1:len(leftMid)+1]
if len(leftPre) > 0 {
n := new(node)
root.left = n
reBuildTree(n, leftPre, leftMid)
}
// 右子樹
rightMid := mid[idx+1:]
rightPre := pre[len(leftMid)+1:]
if len(rightPre) > 0 {
n := new(node)
root.right = n
reBuildTree(n, rightPre, rightMid)
}
}
// 前序遍歷
func preV(root *node) {
if root != nil {
fmt.Print(root.val)
preV(root.left)
preV(root.right)
}
}
// 中序遍歷
func midV(root *node) {
if root != nil {
midV(root.left)
fmt.Print(root.val)
midV(root.right)
}
}
output:
12473568
47215386
2.思路二
func main() {
pre := []int{1, 2, 4, 7, 3, 5, 6, 8} // 根節點
mid := []int{4, 7, 2, 1, 5, 3, 8, 6}
// 排序二叉樹,中序遍歷順序遞增
sortM := make(map[int]int, len(mid))
for i, v := range mid {
sortM[v] = i
}
root := new(node)
root.val = pre[0]
// 按照前序遍歷的順序插入節點
for _, v := range pre {
insert(v, root, sortM)
}
// 前序遍歷
preV(root)
fmt.Println()
// 中序遍歷
midV(root)
fmt.Println()
}
func insert(data int, root *node, sortM map[int]int) {
if sortM[data] < sortM[root.val] {
if root.left != nil {
insert(data, root.left, sortM)
} else {
root.left = &node{val: data}
return
}
} else {
if root.right != nil {
insert(data, root.right, sortM)
} else {
root.right = &node{val: data}
}
}
}
output:
12473568
47215386
