2 solutions

  • 1
    @ 2025-2-4 20:01:59
    #include <bits/stdc++.h>
    
    using namespace std;
    
    struct node {
    	int l, r;//l=左子树编号,r=右子树编号
    	char ch;//节点字母
    };
    node tree[100010];
    int s = 1;//记录子树编号,树根从1开始
    
    void dfsj(int u) {
    	char c;
    	cin >> c;
    	if (c != '.') {
    		//创建节点
    		tree[u].ch = c;
    		//创建节点左子树
    		tree[u].l = ++s;
    		dfsj(tree[u].l);
    		//创建节点右子树
    		tree[u].r = ++s;
    		dfsj(tree[u].r);
    	} else {
    		//节点为空时,直接复制并结束,为后续遍历
    		tree[u].ch = c;
    	}
    }
    
    void dfsz(int u) {//中序遍历
    	if (tree[u].ch != '.') {
    		dfsz(tree[u].l);
    		cout << tree[u].ch;
    		dfsz(tree[u].r);
    	}
    }
    
    void dfsh(int u) {//后序遍历
    	if (tree[u].ch != '.') {
    		dfsh(tree[u].l);
    		dfsh(tree[u].r);
    		cout << tree[u].ch;
    	}
    }
    
    int main() {
    	dfsj(1);
    	dfsz(1);
    	cout << '\n';
    	dfsh(1);
    
    	return 0;
    }
    
    • 1
      @ 2024-1-1 1:46:48
      #include<iostream>
      #include<string>
      using namespace std;
      string a;
      const int N=1e3;//范围
      struct node
      {
      	int l,r;
      }g[N];//树
      int i=-1;
      void f(int &rt)//设置树的函数
      {
      	if(a[++i]!='.' && i <a.size())//为"."时
      	{
      		rt=i;//设置头
      		f(g[rt].l);//左边
      		f(g[rt].r);//右边
      	}
      	else
      	{
      		rt=-1;//返回
      	}
      }
      void mid(int rt)//中序遍历
      {
      	if(rt!=-1)
      	{
      		mid(g[rt].l);//左边
      		cout<<a[rt];//输出
      		mid(g[rt].r);//右边
      	}
      }
      void end(int rt)//后序遍历
      {
      	if(rt!=-1)
      	{
      		end(g[rt].l);//左边
      		end(g[rt].r);//右边
      		cout<<a[rt];//输出
      	}
      }
      int main()
      {
      	cin>>a;//输入
      	int rot=0;//设置根
      	f(rot);//设置树
      	mid(rot);//中序遍历
      	cout<<endl;
      	end(rot);//后序遍历
      	return 0;//完结散花,真辛苦!!!
      }
      
      • 1

      Information

      ID
      825
      Time
      1000ms
      Memory
      256MiB
      Difficulty
      6
      Tags
      # Submissions
      83
      Accepted
      25
      Uploaded By