hooluupog
2014-09-11 00:54:51 +08:00
刚刚写了一个,只随便验证了几个数据点,对错不敢保证。
/*
* input preOrder and inOrder list of a binary tree,
* output its postOrder list.
*/
package main
import "fmt"
var illegal bool
func PostOrder(preOrder, inOrder string) string {
if len(preOrder) == 0 || len(inOrder) == 0 {
return ""
}
root := preOrder[0]
i := 0
for i < len(inOrder) && inOrder[i] != root {
i++
}
if i == len(inOrder) {
illegal = true
return ""
}
return PostOrder(preOrder[1:i+1], inOrder[0:i]) +
PostOrder(preOrder[i+1:len(preOrder)], inOrder[i+1:len(inOrder)]) + string(root)
}
func main() {
var preOrder, inOrder string
fmt.Scan(&preOrder, &inOrder)
illegal = false
res := PostOrder(preOrder, inOrder)
if illegal {
fmt.Println("illegal input")
} else {
fmt.Println(res)
}
}