|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | +) |
| 6 | + |
| 7 | +type TreeNode struct{ |
| 8 | + Val int |
| 9 | + Left *TreeNode |
| 10 | + Right *TreeNode |
| 11 | +} |
| 12 | + |
| 13 | +func printPreOrder(root *TreeNode){ |
| 14 | + if root != nil { |
| 15 | + fmt.Printf("%d ", root.Val) |
| 16 | + printPreOrder(root.Left) |
| 17 | + printPreOrder(root.Right) |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +func printInOrder(root *TreeNode){ |
| 22 | + if root != nil { |
| 23 | + printInOrder(root.Left) |
| 24 | + fmt.Printf("%d ", root.Val) |
| 25 | + printInOrder(root.Right) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +func reConstructBinaryTree(pre []int, in []int) *TreeNode { |
| 30 | + if len(pre) != len(in) || len(pre) == 0 { |
| 31 | + return nil |
| 32 | + } |
| 33 | + // find root and root Index in inOrder |
| 34 | + rootVal := pre[0] |
| 35 | + rootIndex := 0 |
| 36 | + for i := 0; i < len(in); i++ { |
| 37 | + if in[i] == rootVal { |
| 38 | + rootIndex = i |
| 39 | + } |
| 40 | + } |
| 41 | + inL, inR := in[:rootIndex], in[rootIndex+1:] |
| 42 | + preL, preR := pre[1:rootIndex+1], pre[rootIndex+1:] |
| 43 | + left := reConstructBinaryTree(preL, inL) |
| 44 | + right := reConstructBinaryTree(preR, inR) |
| 45 | + return &TreeNode{Val: rootVal, Left: left, Right: right} |
| 46 | +} |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +func main() { |
| 51 | + // example |
| 52 | + pre := []int{1,2,4,7,3,5,6,8} |
| 53 | + in := []int{4,7,2,1,5,3,6,8} |
| 54 | + |
| 55 | + fmt.Println("preOder: ", pre) |
| 56 | + fmt.Println("inOrder: ", in) |
| 57 | + |
| 58 | + // Reconstruct |
| 59 | + fmt.Println("\nReconstruct Binary Tree... \n ",) |
| 60 | + root := reConstructBinaryTree(pre, in) |
| 61 | + |
| 62 | + // test |
| 63 | + fmt.Printf("preOder from Tree reconstructed: ") |
| 64 | + printPreOrder(root) |
| 65 | + fmt.Printf("\n") |
| 66 | + |
| 67 | + fmt.Printf("inOder from Tree reconstructed: ") |
| 68 | + printInOrder(root) |
| 69 | + fmt.Printf("\n") |
| 70 | + |
| 71 | + |
| 72 | +} |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | + |
| 87 | + |
| 88 | + |
| 89 | + |
| 90 | + |
| 91 | + |
| 92 | + |
| 93 | + |
| 94 | + |
| 95 | + |
| 96 | + |
0 commit comments