zoukankan      html  css  js  c++  java
  • [jobdu]二叉树的镜像

    树的镜像,这里的做法就是先序遍历的反过来呗。

    #include <iostream>
    #include <vector>
    using namespace std;
    
    void preOrder(vector<vector<int> > &tree, vector<int> &val, vector<int> &ans, int root) {
        if (root == -1) return;
        else {
            ans.push_back(val[root]);
            preOrder(tree, val, ans, tree[root][1]);
            preOrder(tree, val, ans, tree[root][0]);
        }
    }
    
    int main() {
        int n;
        while (cin >> n)
        {
            vector<vector<int> > tree(n+1);
            vector<int> val(n+1);
            for (int i = 1; i <= n; i++) {
                int tmp;
                cin >> tmp;
                val[i] = tmp;
            }
            for (int i = 1; i <= n; i++) {
                char type;
                cin >> type;
                if (type == 'd') {
                    int x, y;
                    cin >> x >> y;
                    tree[i].push_back(x);
                    tree[i].push_back(y);
                }
                else if (type == 'l') {
                    int x;
                    cin >> x;
                    tree[i].push_back(x);
                    tree[i].push_back(-1);
                }
                else if (type == 'r') {
                    int x;
                    cin >> x;
                    tree[i].push_back(-1);
                    tree[i].push_back(x);
                }
                else if (type == 'z') {
                    tree[i].push_back(-1);
                    tree[i].push_back(-1);
                }
            }
            if (n == 0) {
                cout << "NULL" << endl;
                continue;
            }
            vector<int> ans;
            preOrder(tree, val, ans, 1);
            for (int i = 0; i < ans.size() - 1; i++) {
                cout << ans[i] << " ";
            }
            cout << ans[ans.size()-1] << endl;
        }
    }
    

      

  • 相关阅读:
    Day12 文件操作
    Day11 集合、集合操作
    Day10 【小程序】商城管理(购物车小程序的增强版)
    Day8 字符串操作
    Day9 字典操作
    文件操作
    【python练习】购物车程序
    2296 寻找道路
    2661 信息传递(tarjan&拓扑)
    【模板】LCA(tarjan)
  • 原文地址:https://www.cnblogs.com/lautsie/p/3422352.html
Copyright © 2011-2022 走看看