leetcode105-Golang根据前序遍历与中序遍历构建二叉树

Golang根据前序遍历与中序遍历构建二叉树

执行用时:4 ms, 在所有 Go 提交中击败了95.86%的用户
内存消耗:3.9 MB, 在所有 Go 提交中击败了81.48%的用户

解题思路

  • 前序遍历:根节点,左子树,右子树; 数组第一个元素必定是root节点
  • 中序遍历:左子树,根节点,右子树; 利用前序遍历中找到的root节点在中序遍历中找到其对应的索引index,该index即是左子树长度
  • 切割遍历数组: (左子树的前序遍历,左子树的中序遍历), (右子树的前序遍历,右子树的中序遍历)
  • 递归,递归的结束条件为遍历到二叉树的叶子节点,再向下即返回nil,随即回溯,构建整棵二叉树

代码

/**
 * 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
	}
	// 1. 创建根节点
	root := &TreeNode{Val: preorder[0]}
	// 2. 获取根节点在中序遍历数组中的index
	var i int
	for index,value := range inorder{
		if value == preorder[0]{
			i = index
            break
		}
	}
	// 3. 递归
	root.Left = buildTree(preorder[1:i+1],inorder[:i])
	root.Right = buildTree(preorder[i+1:],inorder[i+1:])
	return root
}
原文地址:https://www.cnblogs.com/litchi99/p/13504304.html