从前序与中序遍历序列构造二叉树

题目描述:

根据一棵树的前序遍历与中序遍历构造二叉树。

注意: 你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树:

    3
/
9 20
/
15 7
//go
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func buildTree(preorder []int, inorder []int) *TreeNode {
    if len(preorder) == 0 {
        return nil
    }
    root := &TreeNode{preorder[0], nil, nil}
    i := 0
    // 在inorder里root的下标
    for ; i < len(inorder); i++ {
        if inorder[i] == preorder[0] {
            break
        }
    }
    // root前的长度,即左子树的长度
    stopIndex := len(inorder[:i])+1
    root.Left = buildTree(preorder[1:stopIndex], inorder[:i])
    root.Right = buildTree(preorder[stopIndex:], inorder[i+1:])
    return root
}

解题思路:

preorder第一个元素为root,在inorder里面找到root,在它之前的为左子树(长stopIndex),之后为右子树。

preorder[1]到preorder[stopIndex]为左子树,之后为右子树,分别递归。

地址:https://mp.weixin.qq.com/s/SNfLHNXK9y1aP93m2RJ7RQ

 
 
原文地址:https://www.cnblogs.com/smallleiit/p/13424570.html