剑指offer-004

来源:互联网 发布:侧吸 顶吸 知乎 编辑:程序博客网 时间:2024/06/12 21:33

题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
先序遍历:根左右
中序遍历:左根右
*/
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector pre,vector in) {
//结点个数为0, 或者前序结点个数与中序结点个数不同
if (pre.size() ==0 || in.size() == 0 || pre.size() != in.size()) return NULL;

    //由前序得到根结点    int rootValue = pre[0];    TreeNode *root = new TreeNode(rootValue);    if (pre.size() == 1){        if (pre[0] == in[0]) return root;        else return NULL;    }    //遍历中序序列找到根结点    int rootIn = 0;    while (rootIn < in.size() && in[rootIn] != rootValue){        ++rootIn;    }    //中序序列中没有根结点    if (rootIn == in.size() && in[rootIn] != rootValue) return NULL;    //递归左子树    //计算左子树的前序 和 中序 序列    vector<int> leftPre;    vector<int> leftIn;    for (int i = 1; i <= rootIn; i++){        leftPre.push_back(pre[i]);        leftIn.push_back(in[i-1]);    }    if (leftPre.size() > 0){        root -> left = reConstructBinaryTree(leftPre, leftIn);    }    //递归右子树    vector<int> rightPre;    vector<int> rightIn;    for (int i = rootIn + 1; i < pre.size(); ++i){        rightPre.push_back(pre[i]);        rightIn.push_back(in[i]);    }    if (rightPre.size() > 0){        root -> right = reConstructBinaryTree(rightPre, rightIn);    }    return root;}

};

0 0
原创粉丝点击