Golang二叉树重建,先序中序->后序,先序后序->中序,中序后序->先序
根据先序中序->后序,先序后序->中序,中序后序->先序,构建二叉树的方法,注意根据先序后序构建中序并不是唯一的,下面的代码以字符串模拟,若要还原树结构,将关键部分换成node即可
package main
import "fmt"
func prein2post(preorder string, inorder string) string {
if len(preorder) == 0 {
return ""
}
idx := 0
for inorder[idx] != preorder[0] {
idx++
}
ll := prein2post(preorder[1:1+idx], inorder[:idx])
rr := prein2post(preorder[1+idx:], inorder[idx+1:])
return ll + rr + string(preorder[0])
}
func prepost2in(pre string, post string) string {
if len(pre) == 1 {
return pre
}
idx := 0
for post[idx] != pre[1] {
idx++
}
ll := prepost2in(pre[1:1+idx+1], post[0:idx+1])
rr := prepost2in(pre[1+idx+1:], post[1+idx:len(post)-1])
return ll + string(pre[0]) + rr
}
func inpost2pre(in string, post string) string {
if len(post) == 0 {
return ""
}
cur := post[len(post)-1]
idx := 0
for in[idx] != cur {
idx++
}
ll := inpost2pre(in[:idx], post[:idx])
rr := inpost2pre(in[idx+1:], post[idx:len(post)-1])
return string(cur) + ll + rr
}
func main() {
pre := "ABCDE" // A
in := "CBDAE" // B E
post := "CDBEA" // C D
fmt.Println(prein2post(pre, in) == post)
fmt.Println(prepost2in(pre, post) == in)
fmt.Println(inpost2pre(in, post) == pre)
}

浙公网安备 33010602011771号