1340:【例3-5】扩展二叉树

扩展二叉树

通过给定的先序遍历构造整棵树,然后再对这颗树分别中序遍历和后序遍历。

#include<iostream>
#include<cstring>
using namespace std;
typedef struct TreeNode;
struct TreeNode {
    char val;
    TreeNode *left;
    TreeNode *right;
};
string t;
int pt;
TreeNode* constructTree(){
    if(t[pt]=='.')return nullptr;
    TreeNode* node=new TreeNode();
    node->val=t[pt];
    pt++;node->left=constructTree();
    pt++;node->right=constructTree();
    return node;
}
void midT(TreeNode* node){
    if(!node)return;
    midT(node->left);
    cout<<node->val;
    midT(node->right);
}
void midB(TreeNode* node){
    if(!node)return;
    midB(node->left);
    midB(node->right);
    cout<<node->val;
}
int main(){
    cin>>t;
    TreeNode* root=constructTree();
    midT(root);
    cout<<endl;
    midB(root);
	return 0;
}
posted @ 2021-09-14 17:21  Rekord  阅读(375)  评论(0编辑  收藏  举报