标签:
/**
前序遍历的结果中,第一个结点一定是根结点,然后在中序遍历的结果中查找这个根结点,根结点左边的就是左子树,根结点右边的就是右子树,递归构造出左、右子树即可。
示意图如图所示:
**/
/** * 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<int> pre,vector<int> in) { struct TreeNode *bt = (TreeNode*)malloc(sizeof(TreeNode)); bt->val = pre[0]; int index = 0; for (int i = 0; i < in.size(); i++){ if (pre[0] == in[i]){ index = i; break; } } vector<int> inL; for (int i = 0; i < index; i++) inL.push_back(in[i]); vector<int> inR; for (int i = index+1; i < pre.size(); i++) inR.push_back(in[i]); vector<int> preL; for (int i = 1; i <= inL.size(); i++) preL.push_back(pre[i]); vector<int> preR; for (int i = inL.size()+1; i < pre.size(); i++) preR.push_back(pre[i]); if(index==0) bt->left = NULL; else bt->left = reConstructBinaryTree(preL, inL); if(preR.size() == 0) bt->right = NULL; else bt->right = reConstructBinaryTree(preR, inR); return bt; } };
标签:
原文地址:http://www.cnblogs.com/qianmacao/p/4839660.html