已知前序遍历和中序遍历可以得到原二叉树。
/** * 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 *buildTree(vector<int> &preorder, vector<int> &inorder) { // Start typing your C/C++ solution below // DO NOT write int main() function if(preorder.size()==0) return NULL; return build(preorder,inorder,0,preorder.size(),0); } TreeNode *build(vector<int> &preorder, vector<int> &inorder,int p,int t,int i) { if(t==0) return NULL; TreeNode* head = (TreeNode *)malloc(sizeof(TreeNode)); head->val = preorder[p]; int j = -1; for( j = i;j<t+i;j++) { if(inorder[j] == preorder[p]) break; } head->left = build(preorder,inorder,p+1,j-i,i); head->right = build(preorder,inorder,p+j-i,t-j-i,j+1); return head; } };