Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路: 中序的是 左中右,后序的是 左右中 , 后序的最后一个元素即是根, 之后去中序中查找根的位置,即能求出 左右子树的 序列长度,
进而递归解子问题。
下面的代码存在两个问题,一是空间复杂度高,大数据内存超了,二是如果后序的根元素在中序中多次出现,可能会查找错误,那么要把中序的左子树和后序的左子树进行比较,若排序之后一致,才能采用,本题似乎没有出现这样的问题。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *help(vector<int> &inorder, vector<int> &postorder){ if(postorder.size()==0) return NULL; if(postorder.size()==1) { TreeNode *p = new TreeNode(inorder[0]); return p; } int len = postorder.size(); int root = postorder[len-1]; // cout << root << endl; TreeNode *p = new TreeNode( root); int site; for(int i = 0 ; i < inorder.size() ; i++) if (inorder[i]==root) { site = i; break; } vector<int> inorder_l,inorder_r; vector<int> postorder_l,postorder_r; postorder_l.clear();postorder_r.clear(); inorder_l.clear();inorder_r.clear(); for(int i = 0 ; i < site ; i++) { inorder_l.push_back(inorder[i]); postorder_l.push_back(postorder[i]); } if(site+1 != inorder.size()) { for(int i = site ; i+1 < inorder.size() ; i++) postorder_r.push_back(postorder[i]); for(int i = site+1; i < inorder.size() ; i++) inorder_r.push_back(inorder[i]); } p->left = help(inorder_l,postorder_l); p->right = help(inorder_r,postorder_r); return p; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode *p = help(inorder,postorder); return p; } };
传下标,节约空间
class Solution { public: TreeNode *help(vector<int> &inorder, int a, int b,vector<int> &postorder,int c , int d){ int len = b-a+1; if(len==0) return NULL; if(len==1) { TreeNode *p = new TreeNode(inorder[a]); return p; } int root = postorder[d]; TreeNode *p = new TreeNode( root); int site; for(int i = a ; i <= b ; i++) if (inorder[i]==root) { site = i; break; } int left_len = site - a; int right_len = len - left_len -1; if(left_len>0) p->left = help(inorder,a,site-1,postorder,c, c + left_len-1); if(right_len>0) p->right = help(inorder,site+1, b,postorder,c+left_len, d-1); return p; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function size_t len = inorder.size(); if(len == 0) return NULL; TreeNode *p = help(inorder,0,len-1,postorder,0,len-1); return p; } };