面试题07.重建二叉树
🔗链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
解题思路:分治算法
同柳神博客里面的两个例子:
🔗==已知后序与中序输出前序(先序)==链接:https://www.liuchuo.net/archives/2090
🔗已知前序(先序)与中序输出后序链接:https://www.liuchuo.net/archives/2087
AC代码:
/**
* 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 helpfx(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
}
TreeNode* helpfx(vector<int>::iterator pre_start,vector<int>::iterator pre_end,
vector<int>::iterator in_start,vector<int>::iterator in_end
){
if(in_end==in_start) return NULL;
TreeNode *t=new TreeNode(*pre_start);
auto root=find(in_start,in_end,*pre_start);
t->left=helpfx(pre_start+1,pre_start+1+(root-in_start),in_start,root);
t->right=helpfx(pre_start+1+(root-in_start),pre_end,root+1,in_end);
return t;
}
};