105. 从前序与中序遍历序列构造二叉树 思路:根据root节点,将中序vector划分成vin_left,vin_right两部分中序子序列,根据中序子序列长度,将前序vector划分成pre_left, pre_right对应的前序子序列。root->left递归生成,root->right递归。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* rebuild(vector<int>& preorder,int preRight,int preLeft,vector<int>& inorder,int inoRight,int inoLeft){ if(preRight>preLeft||inoRight>inoLeft) return nullptr; TreeNode* root=new TreeNode(preorder[preRight]); for(auto i=0;i<=inoLeft;++i){ if(preorder[preRight]==inorder[i]){ root->left=rebuild(preorder,preRight+1,i-inoRight+preRight,inorder,inoRight,i-1); root->right=rebuild(preorder,i-inoRight+preRight+1,preLeft,inorder,i+1,inoLeft); } } return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if(preorder.empty()||inorder.empty()) return nullptr; return rebuild(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1); } };106.从中序与后序遍历序列构造二叉树
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* rebuild(vector<int>& inorder,int inoLeft,int inoRight,vector<int>& postorder,int posLeft,int posRight){ if(inoLeft>inoRight||posLeft>posRight) return nullptr; TreeNode* root=new TreeNode(postorder[posRight]); for(auto i=0;i<=inoRight;++i){ if(inorder[i]==postorder[posRight]){ root->left=rebuild(inorder,inoLeft,i-1,postorder,posLeft,i-inoLeft+posLeft-1); root->right=rebuild(inorder,i+1,inoRight,postorder,i-inoLeft+posLeft,posRight-1); break; } } return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if(inorder.empty()||postorder.empty()) return nullptr; return rebuild(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1); } };