题解 | #重建二叉树#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/**
-
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 pre,vector vin) { if(pre.size()==0||vin.size()==0) return NULL; int length1=pre.size(); int length2=vin.size(); int i=0; //TreeNode a(pre[0]); TreeNode* p=new TreeNode(pre[0]); //p=&a; for(;i<length2;i++) if(pre[0]==vin[i]) break; if(i<=0) p->left=NULL; else { vector pre1,vin1; int j=0; for(j=0;j<i;j++) vin1.push_back(vin[j]); for(j=1;j<1+vin1.size();j++) { pre1.push_back(pre[j]); } p->left=reConstructBinaryTree(pre1,vin1); } if(i>=length2-1) p->right=NULL; else { vector pre1,vin1; int j=0; for(j=i+1;j<length2;j++) vin1.push_back(vin[j]); for(j=0;j<length1;j++) for(int k=0;k<vin1.size();k++) if(pre[j]==vin1[k]) pre1.push_back(pre[j]); p->right=reConstructBinaryTree(pre1,vin1); } return p;
} };