美文网首页二叉树
【剑指 offer】- 重建二叉树(先/中遍历)

【剑指 offer】- 重建二叉树(先/中遍历)

作者: 邓泽军_3679 | 来源:发表于2019-04-06 10:48 被阅读0次

    1、题目描述

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

    • 注意:

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

    • 样例

    给定:
    前序遍历是:[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

    2、问题描述:

    • 已知先序和中序遍历,求重建二叉树。

    3、问题关键:

    • 要指导先序和中序的关系。
    • 先序的 第一个是根结点,可以根据根结点在中序中的位置,找到左子树和右子树。
    • 左子树和右子树也都是先序和中序遍历。

    4、C++代码:

    /**
     * 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;
            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;
        }
    };
    

    相关文章

      网友评论

        本文标题:【剑指 offer】- 重建二叉树(先/中遍历)

        本文链接:https://www.haomeiwen.com/subject/emxriqtx.html