一些分界点自己手动模拟一下会比较清楚
/**
* 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:
vector<int> preorder, inorder;
map<int, int> mp;
TreeNode* buildTree(vector<int>& _preorder, vector<int>& _inorder) {
preorder = _preorder, inorder = _inorder;
for(int i = 0; i < inorder.size(); i ++ ) mp[inorder[i]] = i;
return dfs(0, preorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode* dfs(int pl, int pr, int il, int ir){
if(pl > pr) return NULL;
TreeNode* root = new TreeNode(preorder[pl]);
int p = mp[preorder[pl]];
root->left = dfs(pl + 1, pl + 1 + p - il - 1, il, p - 1);
root->right = dfs(pl + 1 + p - il - 1 + 1, pr, p + 1, ir);
return root;
}
};
您好,请问为啥中序和后序重建不能这样做呀
也可以的,中序+后续是可以确定一颗二叉树的,只是代码需要修改一部分;