题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
通过先序遍历和中序遍历构造二叉树。大概思路是递归的构造,因为先序遍历总是先访问根结点,所以很容易从先序列表中得到根,位于该结点右侧的就是子树,再由这个根结点从中序列表中找到,位于该值左侧的就是左子树,右侧的即为又子树。然后分别用同样的方法构建左、右子树,直到构造完成。代码:
1 TreeNode *buildTree(vector &preorder, vector &inorder) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 int preIdx=0; 5 return buildTree(preorder,inorder,&preIdx,0,inorder.size()); 6 } 7 TreeNode* buildTree(vector & preorder,vector & inorder,int* preIdx,int inIdx,int inLen){ 8 if(preorder.size()==*preIdx||inLen==0) return NULL; 9 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));10 root->val = preorder[*preIdx];11 root->left=NULL;12 root->right=NULL;13 int i=inIdx;14 while(i-inIdxval) break;16 i++;17 }18 if(i-inIdx>0&&*preIdx left=buildTree(preorder,inorder,&(++*preIdx),inIdx,i-inIdx);20 if(inLen-(i-inIdx)-1>0&&*preIdx right=buildTree(preorder,inorder,&(++*preIdx),i+1,inLen-(i-inIdx)-1);22 return root;23 }