题目
前序+中序->建树
解题思路
思路 01
前序确定根(第一个),中序用根分割左根右
思路 02
借助hashmap,优化每次中序中需要查找根索引的操作
Code
Code 01
/**
* 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* buildTree(vector<int>& preorder, vector<int>& inorder) {
return generate_tree(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1);
}
private:
TreeNode * generate_tree(vector<int>& preorder, vector<int>& inorder, int pl, int pr, int il, int ir){
if(il>ir)return NULL;
int k=il;
while(k<ir&&inorder[k]!=preorder[pl])k++; //中序中找到当前根节点
TreeNode* root=new TreeNode(preorder[pl]);
root->left=generate_tree(preorder,inorder,pl+1,pl+(k-il),il, k-1);
root->right=generate_tree(preorder,inorder,pl+(k-il)+1,pr,k+1, ir);
return root;
}
};