1 条题解

  • 0
    @ 2025-11-30 16:27:51

    C :

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    char s[200],t[100];
    int l[100],r[100];
    int n,j,k;
    
    void tree(int f,int p) {
    	int i;
    	j++;
        if (s[j]=='.') {if (f==0) l[p]=0;else r[p]=0;}
    	else {
    		k++;i=k;
    		t[k]=s[j];
    		if (f==0) l[p]=i;else r[p]=i;
    		tree(0,i);
    		tree(1,i);
    	}
    }
    
    void tree_z(int i){
    	if (l[i]>0) tree_z(l[i]);
    	printf("%c",t[i]);
    	if (r[i]>0) tree_z(r[i]);
    }
    
    void tree_h(int i){
    	if (l[i]>0) tree_h(l[i]);
    	if (r[i]>0) tree_h(r[i]);
    	printf("%c",t[i]);
    }
    
    int main(){
    	scanf("%s",s);
    	n=strlen(s)-1;
    	j=0;k=1;
        t[k]=s[j];
    	tree(0,1);
    	tree(1,1);
        //int i;
    	//for (i=1;i<=k;i++)
    	//	printf("%c %d %d\n",t[i],l[i],r[i]);
    	tree_z(1);
    	printf("\n");
    	tree_h(1);
    	printf("\n");
    	return 0;
    }
    
    

    C++ :

    #include <iostream>
    #include <string>
    #include <cstdio>
    using namespace std;
    
    struct BNode {
    	char ch;
    	int lchild, rchild;
    } node[101];
    
    int root = 0, cnt = 0;
    
    // 创建二叉树 
    int buildTree(int T);
    // 中序遍历
    void inOrder(int T);
    // 后序遍历
    void postOrder(int T);
    int main()
    {
    	root = buildTree(0);
    	inOrder(root);
    	cout << endl;
    	postOrder(root);
    	//cout << root << endl;
    	return 0;
    }
    
    // 创建二叉树 ABD..EF..G..C..
    int buildTree(int T) {
    	char ch;
    	cin >> ch;
    	if (ch == '.') {
    		return 0;
    	}
    
    	else {
    		T = ++cnt;
    		node[T].ch = ch;
    		node[T].lchild = buildTree(T);
    		node[T].rchild = buildTree(T);
    	}
    	return T;
    }
    
    // 中序遍历
    void inOrder(int T) {
    	if (T) {
    		inOrder(node[T].lchild);
    		cout << node[T].ch;
    		inOrder(node[T].rchild);
    	}
    }
    // 后序遍历
    void postOrder(int T) {
    	if (T) {
    		postOrder(node[T].lchild);
    		postOrder(node[T].rchild);
    		cout << node[T].ch;
    	}
    }
    
    • 1

    信息

    ID
    1436
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    (无)
    递交数
    0
    已通过
    0
    上传者