《剑指offer刷题笔记》6、重建二叉树 【c++详细题解】

题目

输入一棵二叉树前序遍历和中序遍历的结果,请重建该二叉树。

注意:

  • 二叉树中每个节点的值都互不相同;
  • 输入的前序遍历和中序遍历一定合法;

样例

给定:
前序遍历是:[3, 9, 20, 15, 7]
中序遍历是:[9, 3, 15, 20, 7]

返回:[3, 9, 20, null, null, 15, 7, null, null, null, null]
返回的二叉树如下所示:
    3
   / \
  9  20
    /  \
   15   7

思路

(递归) O ( n ) O(n) O(n)

递归建立整棵二叉树:先递归创建左右子树,然后创建根节点,并让指针指向两棵子树。

具体步骤如下:

  1. 先利用前序遍历 找根节点:前序遍历的第一个数,就是根节点的值;
  2. 在中序遍历中找到根节点的位置 k,则 k 左边是左子树的中序遍历,右边是右子树的中序遍历;
  3. 假设左子树的中序遍历的长度是 l,则在前序遍历中,根节点后面的 l 个数,是左子树的前序遍历,剩下的数是右子树的前序遍历;
  4. 有了左右子树的前序遍历和中序遍历,我们可以先递归创建出左右子树,然后再创建根节点;

时间复杂度分析

我们在初始化时,用哈希表(unordered_map<int,int>)记录每个值在中序遍历中的位置,这样我们在递归到每个节点时,在中序遍历中查找根节点位置的操作,只需要 O ( 1 ) O(1) O(1)的时间。此时,创建每个节点需要的时间是 O ( 1 ) O(1) O(1),所以总时间复杂度是 O ( n ) O(n) O(n)

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:

    unordered_map<int,int> pos;

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    
    
        int n = preorder.size();
        for (int i = 0; i < n; i ++ )
            pos[inorder[i]] = i; //将根节点的位置记录下来
        return dfs(preorder, inorder, 0, n - 1, 0, n - 1);//递归创建左右子树,最后将根节点指向左右子树
    }

    TreeNode* dfs(vector<int>&pre, vector<int>&in, int pl, int pr, int il, int ir)
    {
    
    
        if (pl > pr) return NULL; //如果左区间大于右区间,直接返NULL
        int k = pos[pre[pl]] - il; //前序遍历区间的长度
        TreeNode* root = new TreeNode(pre[pl]);//创建根节点
        root->left = dfs(pre, in, pl + 1, pl + k, il, il + k - 1); //左子树的前序和中序遍历区间
        root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir);//右子树的前序和中序遍历区间
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45629285/article/details/115441269