leetcode106-根据中序和后续遍历构建二叉树

根据中序和后续遍历构建二叉树

  • 中序遍历:左子树,根节点,右子树
  • 后序遍历: 左子树,右子树,根节点
  • 后序遍历的最后一个元素即根节点的值
  • 根节点在中序遍历中的索引index等于左子树长度

代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func buildTree(inorder []int, postorder []int) *TreeNode {
	if len(inorder) == 0{
		return nil
	}
    l := len(postorder)-1			// root节点所在位置的index
	rootVal := postorder[l]			// 获得root节点
	root := &TreeNode{Val: rootVal} // 构建根节点
	// root := new(TreeNode)
	// root.Val = rootVal
	i :=0							// 查找根节点在中序遍历中的位置index
	for ;i<len(inorder);i++{
		if inorder[i] == rootVal{
			break
		}
	}
	// i可以理解为是左子树的长度
	// 在中序遍历中,inorder[:i]即左子树的元素; 在后序遍历中,postorder[:i]也为左子树的元素
	root.Left = buildTree(inorder[:i],postorder[:i])
	// 在中序遍历中,inorder[i+1:]为右子树的元素,i为根节点,i+1即把根节点剔除 
	// 在后序遍历中,postorder[i:l]为右子树的元素,切片截取为左闭右开,此处获取不到l对应的根节点原素
	root.Right = buildTree(inorder[i+1:],postorder[i:l])
	return root
}
原文地址:https://www.cnblogs.com/litchi99/p/13504302.html