Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]
Return the following binary tree:
3 / 9 20 / 15 7
前序、中序遍历得到二叉树,可以知道每一次前序新数组的第一个数为其根节点。在中序遍历中找到根节点对应下标,根结点左边为其左子树,根节点右边为其右子树,再根据中序数组中的左右子树个数,找到对应的前序数组中的左右子树新数组。设每次在中序数组中对应的位置为i,则对应的新数组为:
前序新数组:左子树[pleft+1,pleft+i-ileft],右子树[pleft+i-ileft+1,pright]
中序新数组:左子树[ileft,i-1],右子树[i+1,iright] C++
1 TreeNode* buildTree(vector<int>& preorder,int pleft,int pright,vector<int>& inorder,int ileft,int iright){ 2 if(pleft>pright||ileft>iright) 3 return NULL; 4 int i=0; 5 for(i=ileft;i<=iright;i++){ 6 if(preorder[pleft]==inorder[i]) 7 break; 8 } 9 TreeNode* cur=new TreeNode(preorder[pleft]); 10 cur->left=buildTree(preorder,pleft+1,pleft+i-ileft,inorder,ileft,i-1); 11 cur->right=buildTree(preorder,pleft+i-ileft+1,pright,inorder,i+1,iright); 12 return cur; 13 } 14 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { 15 return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1); 16 }