已知二叉樹前序遍歷和中序遍歷的結果,重建二叉樹node
解決思路:數組
例如 pre=[1,2,4,7,3,5,6,8] mid=[4,7,2,1,5,3,8,6]ui
最終二叉樹爲[1,2,3,4,null,5,6,null,7,null,null,null,null,8]code
1 2 3 4 5 6 7 8
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
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