数据结构与算法-15.从前序与中序遍历序列构造二叉树

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

题目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IdO3DVwv-1636428832110)(image-20211109111009384.png)]

15.0、递归解法

先序序列【3,9,20,15,7】

中序序列【9,3,15,20,7】

  • 先序的第一个就是整个树的根
  • 中序中以根为分界线,左边为左子树的中序,右边为右子树的中序
  • 根据在先序序列里找到的根,把中序序列分为两个子树的中序序列
  • 然后重复上述步骤

至于怎么在先序序列中找到子树的根

  • 先序序列可以拆分为【3】,【9】,【20,15,7】
  • 第一块是整个树的根,第二块是左子树的根,第三块是右子树的根
  • 可以根据中序序列来判断左子树有多少个节点,这样就可以拿到左子树的先序遍历序列,也就可以拿到左子树的根了
unordered_map<int, int> data;
TreeNode* buildTree0(vector<int>& preorder, vector<int>& inorder) 
{
    int size = preorder.size();
    for (int i = 0; i < size; i++)         //用哈希映射来减少查询的时间
        data.insert({ inorder[i],i });
    return recursion(preorder, inorder, 0, size - 1, 0, size - 1);
}
//该递归包含的内容是,创建根节点,然后连接其左右子节点,最后返回根节点
TreeNode* recursion(vector<int>& preorder, vector<int>& inorder, int preLeftIndex, int preRightIndex, int inLeftIndex, int inRightIndex)
{
    if (preLeftIndex > preRightIndex)return NULL;
    int midNodeIndex = data[preorder[preLeftIndex]];         //先序遍历的第一个就是根节点,再通过哈希映射找到在中序遍历中的位置
    TreeNode* root = new TreeNode(inorder[midNodeIndex]);   //创建根节点
    root->left = recursion(preorder, inorder, preLeftIndex + 1, preLeftIndex + midNodeIndex - inLeftIndex, inLeftIndex, midNodeIndex - 1);
    root->right = recursion(preorder, inorder, preLeftIndex + midNodeIndex - inLeftIndex + 1, preRightIndex, midNodeIndex + 1, inRightIndex);
    return root;
}
  • 时间复杂度:O(n)还有哈希映射的占用空间n
  • 空间复杂度:O(n)

15.1、迭代解法

这个博主讲不好(水平有限),可以参考网上大佬的思路,这里仅提供代码。

TreeNode* buildTree1(vector<int>& preorder, vector<int>& inorder)
{
    int size = preorder.size();
    stack<TreeNode*> stk;
    TreeNode* root = new TreeNode(preorder[0]);
    stk.push(root);                     //先将preorder的第一个入栈
    int inorderIndex = 0;               //中序的指针
    for (int preIndex = 1; preIndex < size; preIndex++)
    {
        TreeNode* tempNode = stk.top();
        if (tempNode->val != inorder[inorderIndex])
        {
            tempNode->left = new TreeNode(preorder[preIndex]);
            stk.push(tempNode->left);
        }
        else
        {
            while (!stk.empty() && stk.top()->val == inorder[inorderIndex])
            {
                tempNode = stk.top();
                stk.pop();
                inorderIndex++;
            }
            tempNode->right = new TreeNode(preorder[preIndex]);
            stk.push(tempNode->right);
        }

    }
    return root;
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)不考虑结果占用,最坏情况为n
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值