递归的方法利用先序遍历和中序遍历构建二叉树,同样也可以利用到中序遍历和后序遍历构建二叉树。
//利用先序遍历和中序遍历构建二叉树 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { TreeNode *root=NULL; if(preorder.size()==0||inorder.size()==0||preorder.size()!=inorder.size()) return root; root=tree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1); return root; } TreeNode* tree(vector<int>&preorder,int preBegin,int preEnd,vector<int>&inorder,int inBegin,int inEnd){ TreeNode *root=NULL; if(preorder.size()==0||inorder.size()==0||preorder.size()!=inorder.size()) return root; TreeNode *leftNode=NULL; TreeNode *rightNode=NULL; root->val=preorder[preBegin]; int rootVal=root->val; int i; for(i=inBegin;i<=inEnd;i++) if(inorder[i]==root->val) break; if(i>inEnd) return root; int leftLen=i-inBegin; int rightLen=inEnd-i-1; leftNode=buildTree(preorder,preBegin+1,preBegin+leftLen,inorder,inBegin,inBegin+leftLen); rightNode=buildTree(preorder,preBegin+1+leftLen,preEnd,inorder,i+1,i+rightLen); root->left=leftNode; root->right=rightNode; return root; }
时间: 2024-10-11 12:43:00