思路:先序的第一个元素和后序的最后一个元素是当前子树的根,然后遍历中序序列,找到左右子树的分界线,递归建左子树和右子树。
class Solution { public: /*由于是oj,这里假设给的序列是合法的,正常情况是需要判断不合法情况的 */ TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder,int instart,int inend,int poststart,int postend) { TreeNode* root = new TreeNode(postorder[postend]); if(instart == inend && poststart == postend && instart == poststart)return root; int i; for(i = instart;i <= inend;++i) { if(inorder[i] == postorder[postend])break;//找到中序的根节点 } if(i > instart)root -> left = buildTree(inorder,postorder,instart,i - 1,poststart,poststart + (i - instart - 1)); if(i < inend) root -> right = buildTree(inorder,postorder,i + 1,inend,poststart + i - instart,postend - 1); return root; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { int inlength = inorder.size(),postlength = postorder.size(); if( inlength == 0 || inlength != postlength ) return NULL; return buildTree(inorder,postorder,0,inlength-1,0,postlength-1); } }; class Solution { public: TreeNode *buildTree(vector<int>& preorder,vector<int> &inorder,int prestart,int preend,int instart,int inend) { TreeNode* root = new TreeNode(preorder[prestart]); if(instart == inend && prestart == preend && instart == prestart)return root; int i; for(i = instart;i <= inend;++i) { if(inorder[i] == preorder[prestart])break;//找到中序的根节点 } if(i > instart)root -> left = buildTree(preorder,inorder,prestart+1,prestart + i - instart,instart,i - 1); if(i < inend) root -> right = buildTree(preorder,inorder,prestart + i - instart + 1,preend,i + 1,inend); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int prelength = preorder.size(),inlength = inorder.size(); if( inlength == 0 || inlength != prelength ) return NULL; return buildTree(preorder,inorder,0,prelength-1,0,inlength-1); } };
时间: 2024-12-20 12:53:01