【编程-剑指offer】重建二叉树

3、重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。。

知识点

:

二叉树遍历

解题思路

输入的是前序遍历及中序遍历的结果,如示例:
前序 : 1 2 4 7 3 5 6 8
中序 : 4 7 2 1 5 3 8 6

通过前序找根节点,通过中序找左右子树
前序的第一个节点是根节点,在中序中找到根节点的位置,在根节点左侧的子串是左子树,在根节点右侧的子串是右子树。然后再分别将两个子串提出来进行子树的构建。直到提出来的子串为0

代码块

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.empty() && vin.empty())return NULL;
        int len = pre.size();
        TreeNode* root = new TreeNode(pre[0]) ; //pre的第一个节点永远是根节点
        int root_id = 0;//记录root在中序中的下标
        int leftlen;
        int riglen;
        for(int i = 0; i<vin.size(); i++){
            if(vin[i] == pre[0]){
                root_id = i;
                break;
            }
        }
        vector<int> lef_t,vin_t,rig_t;
        for(int i = 0; i<len; i++){
            if(i<root_id)
                lef_t.push_back(vin[i]); 
            else if(i>root_id)
                rig_t.push_back(vin[i]);
        }
        vector<int> lef_son_pre(pre.begin()+1,pre.begin()+root_id+1);
        vector<int> left_son_in(vin.begin(),vin.begin()+root_id);
        vector<int> right_son_pre(pre.begin()+root_id+1,pre.end());
        vector<int> right_son_in(vin.begin()+root_id+1,vin.end());
        root->left = reConstructBinaryTree(lef_son_pre,left_son_in);
        root->right = reConstructBinaryTree(right_son_pre,right_son_in);
        return root;

    }
};

猜你喜欢

转载自blog.csdn.net/qq_20135597/article/details/82155257