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 *buildTree_in(vector<int> &inorder, vector<int> &postorder, int in_start, int post_start, int len) { TreeNode* root=NULL; if(len==0) return NULL; if(len==1) return new TreeNode(inorder[in_start]); int i=0; while(inorder[in_start+i]!=postorder[post_start+len-1]) i++; root=new TreeNode(postorder[post_start+len-1]); root->left=buildTree_in(inorder,postorder,in_start,post_start,i); root->right=buildTree_in(inorder,postorder,in_start+i+1,post_start+i,len-i-1); return root; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { int len=(int)inorder.size(); if(len==0) return NULL; if(len==1) return new TreeNode(inorder[0]); return buildTree_in(inorder,postorder,0,0,len); } };
update:
2014 - 12- 22
其实和上面的思路是基本一样的,只是函数参数略有改变。
class Solution { public: TreeNode *buildTree(vector<int> &inorder, int in_start, int in_end, vector<int> &postorder, int post_start, int post_end) { TreeNode* root = new TreeNode(postorder[post_end]); if (post_start > post_end) return NULL; else if (post_start == post_end) { return root; } int index = 0; int left_length = 0; for (index = in_start; index <= in_end; ++index) { if (inorder[index] == postorder[post_end]) break; } left_length = index - in_start; root->left = buildTree(inorder, in_start, index - 1, postorder, post_start, post_start + left_length - 1); root->right = buildTree(inorder, index+1, in_end, postorder, post_start + left_length, post_end - 1); return root; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if (inorder.size() == 0 || postorder.size() == 0) return NULL; return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); } };