二叉樹的重建

已知二叉樹前序遍歷和中序遍歷的結果,重建二叉樹node

解決思路:數組

  • 前序遍歷的結果中根節點在左右孩子的前面,左孩子在右孩子前面;中序遍歷的結果中根節點在左右孩子的中間,中序遍歷能夠找出根節點的左子樹和右子樹,前序遍歷的第一個節點是根節點,根據這些特性能夠遞歸的重建二叉樹

例如 pre=[1,2,4,7,3,5,6,8] mid=[4,7,2,1,5,3,8,6]ui

  1. 1做爲根節點,左子樹[4,7,2] 右子樹[5,3,8,6]
  2. 左子樹[4,7,2]中因爲前序遍歷結果2在前面,因此2位左子樹根節點;同理3是右子樹根節點;所以2有左子樹[4,7]沒右子樹,3有左子樹5,右子樹[8,6]
  3. [4,7]因爲前序遍歷中4在前面,因此4是根節點,4右子樹爲[7];同理[8,6]中6爲根節點,[8]是左子樹
  4. 最終二叉樹爲[1,2,3,4,null,5,6,null,7,null,null,null,null,8]code

    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
相關文章
相關標籤/搜索