题目描述:
根据树的三种遍历方式中任意两种方式的组合(前序,中序,后序)进行二叉树的构造。
方法一:递归
答题模板:
class Solution {
public:
TreeNode* creattree(vector<int>&xxx,vector<int>&yyy,int left1,int right1,int left2,int right2){
if(left1>right1||left2>right2)return NULL;
TreeNode* root=new TreeNode(...);//先找到1遍历顺序中的根节点
int rootin=...;
while(...)rootin++;//找到2遍历顺序中,这个根节点的位置
int len=rootin-...;//2遍历中左子树的长度
root->left=creattree(xxx,yyy,...,...,...,...);//分别在1,2遍历中找到不同的左右子树对应的位置
root->right=creattree(xxx,yyy,...,...,...,...);
return root;
}
TreeNode* buildTree(vector<int>& xxx, vector<int>& yyy) {
return creattree(xxx,yyy,0,xxx.size()-1,0,yyy.size()-1);
}
};
方法二:非递归
- 构造左子树,出现相等,构造一颗右子树。两个指针从头开始
//preorder and inorder:
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()==NULL)return NULL;
stack<TreeNode*>nodes;
int i=1,j=0;
TreeNode* root=new TreeNode(preorder[0]);
TreeNode* cur = root;
nodes.push(cur);
while(i<preorder.size()){
if(cur->val == inorder[j]){
while(!nodes.empty()&&nodes.top()->val == inorder[j]){//找到放右节点的根节点
cur=nodes.top();
nodes.pop();
j++;
}
cur->right=new TreeNode(preorder[i]);
cur=cur->right;
nodes.push(cur);
i++;
}
else {//先把左节点都放进去
cur->left=new TreeNode(preorder[i]);
cur=cur->left;
nodes.push(cur);
i++;
}
}
return root;
}
};
- 构造右子树,出现相等,构造一颗左子树。两个指针从尾开始
//inorder and postorder
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(inorder.size()==0)return NULL;
stack<TreeNode*>nodes;
int i=inorder.size()-1,j=postorder.size()-1;
TreeNode* root=new TreeNode(postorder[j]);
TreeNode* cur = root;
nodes.push(cur);
j--;
while(j>=0){
if(cur->val == inorder[i]){
while(!nodes.empty()&& nodes.top()->val == inorder[i]){//找到放左子树的根节点
cur=nodes.top();
nodes.pop();
i--;
}
cur->left=new TreeNode(postorder[j]);
cur=cur->left;
nodes.push(cur);
j--;
}
else {//先构造右子树
cur->right=new TreeNode(postorder[j]);
cur=cur->right;
nodes.push(cur);
j--;
}
}
return root;
}
};
- 如果左子树不存在就一直构造左子树,遇到栈顶元素和post数组中元素相同就回溯
//preorder and postorder
class Solution {
public:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
if (pre.empty()) return NULL;
stack<TreeNode*> S;
auto root = new TreeNode(pre[0]);
S.push(root);
for (int i = 1, j = 0; i < pre.size(); i++) {
auto node = new TreeNode(pre[i]);
while (S.top()->val == post[j]) S.pop(), j++; // 回溯
if (!S.top()->left)
S.top()->left = node;
else
S.top()->right = node;
S.push(node);
}
return root;
}
};