105. 从前序与中序遍历序列构造二叉树
链接:
链接: 105. 从前序与中序遍历序列构造二叉树C++
描述:
代码:
class Solution {
public:
TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,
int& prei,int inbegin,int inend){
if(inbegin>inend) return NULL;
TreeNode* root = new TreeNode(preorder[prei]);
int rooti = inbegin;
while(rooti<=inend){
if(inorder[rooti]==preorder[prei]){
break;
}
else{
++rooti;
}
}
++prei;
root->left=_buildTree(preorder,inorder,prei,inbegin,rooti-1);
root->right=_buildTree(preorder,inorder,prei,rooti+1,inend);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int prei = 0;
return _buildTree(preorder,inorder,prei,0,inorder.size()-1);
}
};
解析:
106. 从中序与后序遍历序列构造二叉树
链接:
链接: 106. 从中序与后序遍历序列构造二叉树
描述:
代码:
class Solution {
int post_idx;
unordered_map<int, int> idx_map;
public:
TreeNode* helper(int in_left, int in_right, vector<int>& inorder, vector<int>& postorder){
if (in_left > in_right) return nullptr;
int root_val = postorder[post_idx];
TreeNode* root = new TreeNode(root_val);
int index = idx_map[root_val];
post_idx--;
root->right = helper(index + 1, in_right, inorder, postorder);
root->left = helper(in_left, index - 1, inorder, postorder);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
post_idx = (int)postorder.size() - 1;
int idx = 0;
for (auto& val : inorder) {
idx_map[val] = idx++;
}
return helper(0, (int)inorder.size() - 1, inorder, postorder);
}
};
解析:
中序:确定左右子树 后序:从后往前,确定根节点
|