【go】力扣106_从中序与后序遍历序列构造二叉树

32 篇文章 0 订阅

题目描述:

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

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

例如,给出

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

    3
   / \
  9  20
    /  \
   15   7

 解题思路:

递归,利用中序和后序遍历二叉树的特点,后序遍历最末尾为根节点,找到根节点在中序遍历对应位置,以此为分界线,左侧为左子树节点集合,右侧为右子树节点集合

我的写法:

func buildTree(inorder []int, postorder []int) *TreeNode {
    var treeBuild = new(TreeNode)
	if len(inorder) == 0 || len(postorder) == 0{
		return nil
	}
    treeBuild.Val = postorder[len(postorder)-1]
	if len(inorder) == 1 || len(postorder) == 1{
		return treeBuild
	}
	for i,v :=range inorder{
		if v == postorder[len(postorder)-1]{
			treeBuild.Left = buildTree(inorder[:i],postorder[:i])
			treeBuild.Right = buildTree(inorder[i+1:],postorder[i:len(postorder)-1])
		}
	}
	return treeBuild
}

官方写法:

func buildTree(inorder []int, postorder []int) *TreeNode {
    idxMap := map[int]int{}
    for i, v := range inorder {
        idxMap[v] = i
    }
    var build func(int, int) *TreeNode
    build = func(inorderLeft, inorderRight int) *TreeNode {
        // 无剩余节点
        if inorderLeft > inorderRight {
            return nil
        }

        // 后序遍历的末尾元素即为当前子树的根节点
        val := postorder[len(postorder)-1]
        postorder = postorder[:len(postorder)-1]
        root := &TreeNode{Val: val}

        // 根据 val 在中序遍历的位置,将中序遍历划分成左右两颗子树
        // 由于我们每次都从后序遍历的末尾取元素,所以要先遍历右子树再遍历左子树
        inorderRootIndex := idxMap[val]
        root.Right = build(inorderRootIndex+1, inorderRight)
        root.Left = build(inorderLeft, inorderRootIndex-1)
        return root
    }
    return build(0, len(inorder)-1)
}

复杂度分析

时间复杂度:O(n),其中 nn 是树中的节点个数。

空间复杂度:O(n)。我们需要使用 O(n) 的空间存储哈希表,以及 O(h)(其中 hh 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为 O(n)。

 作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/cong-zhong-xu-yu-hou-xu-bian-li-xu-lie-gou-zao-14/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值