1 条题解

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

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    
    int n, h[30], root;
    struct node {
    	char val;
    	int fa, l, r;
    }a[30];
    
    void prev_order(int u) {
    	if (!u) return;
    	
    	cout << a[u].val;
    	prev_order(a[u].l);
    	prev_order(a[u].r);
    }
    
    void post_order(int u) {
    	if (!u) return;
    	
    	post_order(a[u].l);
    	post_order(a[u].r);
    	cout << a[u].val;
    }
    
    int main() {
    	cin >> n;
    	for (int i = 1; i <= n; i ++) {
    		cin >> a[i].val;
    	
    		int x, y;
    		cin >> x;
    		
    		if (x != 0) {
    			a[i].l = x;		//原数中第一个儿子结点作为新树的左儿子 
    			a[x].fa = i;
    			
    			y = x;
    			while (cin >> x && x) {
    				a[y].r = x;	//原数中第一个兄弟结点作为新树的右儿子
    				a[x].fa = y;
    				y = x;
    			}
    		}		
    	}
    	
    	for (int i = 1; i <= n; i ++) {
    		if (!h[i]) {
    			root = i;
    			break;
    		}
    	}
    	
    	prev_order(root);
    	cout << endl;
    	post_order(root);
    
    	return 0;
    }
    
    
    • 1

    信息

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