废话就不多说了,开始。。。
每日一道理
如果你们是蓝天,我愿做衬托的白云;如果你们是鲜花,我愿做陪伴的小草;如果你们是大树,我愿做点缀的绿叶……我真诚地希望我能成为你生活中一个欢乐的音符,为你的每一分钟带去祝福。
如果你们是蓝天,我愿做衬托的白云;如果你们是鲜花,我愿做陪伴的小草;如果你们是大树,我愿做点缀的绿叶……我真诚地希望我能成为你生活中一个欢乐的音符,为你的每一分钟带去祝福。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
//Note:
//You may assume that duplicates do not exist in the tree.
//so we can build an unordered_map O(1) to look up the index in inorder, to divide the left subtree and right subtree
//in postorder.
//inorder{(inStart)left(inRootIdx-1)root(inRootIdx+1)right}, postorder{left(inRootIdx-1)right(PostEnd-1)root}
public:
unordered_map<int, int> m_Value2Index;//inorder map
void BuildMap(vector<int> &inorder)
{
m_Value2Index.clear();
for(int i = 0; i < inorder.size(); ++i)
m_Value2Index[inorder[i]] = i;
}
//just make sure (inHigh-inLow == preHigh-preLow), there will be no problem then
TreeNode* BuildTreeInPlusPre(vector<int> &inorder, int inLow, int inHigh, vector<int> &preorder, int preLow, int preHigh )
{
if(inLow > inHigh || preLow > preHigh)
return NULL;
int rootValue = preorder[preLow];
TreeNode* parent = new TreeNode(rootValue);
int inRootIdx = m_Value2Index[rootValue];
parent->left = BuildTreeInPlusPre(inorder, inLow, inRootIdx-1, preorder, preLow+1, preLow+inRootIdx-inLow);
parent->right = BuildTreeInPlusPre(inorder, inRootIdx+1, inHigh, preorder, preHigh-(inHigh-inRootIdx-1), preHigh);
return parent;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
BuildMap(inorder);
return BuildTreeInPlusPre(inorder, 0, inorder.size()-1, preorder, 0, preorder.size()-1);
}
};
文章结束给大家分享下程序员的一些笑话语录: 某程序员对书法十分感兴趣,退休后决定在这方面有所建树。花重金购买了上等的文房四宝。一日突生雅兴,一番磨墨拟纸,并点上了上好的檀香,颇有王羲之风 范,又具颜真卿气势,定神片刻,泼墨挥毫,郑重地写下一行字:hello world.
---------------------------------
原创文章 By
function和class
---------------------------------