kamacoder-solutions icon indicating copy to clipboard operation
kamacoder-solutions copied to clipboard

51. 平移二叉树(第七期模拟笔试)C++

Open li54426 opened this issue 1 year ago • 1 comments

#include<vector>

#include<algorithm>


#include<iostream>
using namespace std;

// 这一层旋转k , 下一层旋转 2 * k
void myreverse(vector<vector<int> > &tree, int i ,  int k ){
    if(i == tree.size() ){
        return;
    }
    
    // cout<< "i="<< i<< "\tk = "<< k << endl;
    auto &nums = tree[i]; 
    
    if(nums.size() <= k ){
         k = k  % nums.size();
    }
    reverse(nums.begin(), nums.end());
    reverse(nums.begin(), nums.begin() + k);
    reverse(nums.begin() + k, nums.end());
    // 
    // cout<< "调用了"<< "i="<< i+1<< "\tk = "<<2*  k << endl;
    int cnt = 0;
    for(int i = 0; i< k && i< nums.size(); ++i){
        if(nums[i] != -1){
            cnt++;
        }
    }
     myreverse(tree, i+1, 2* cnt);
    
    
}

void printtree(vector<vector<int> > &tree){
    cout<< "tree high = "<< tree.size() << endl;
    for(auto & nums : tree){
        for(int n : nums){
            cout<< n<< ' ';
        }
        cout<< endl;
    }    
}


int main(){
    int k , n;
    cin>> k >> n;
    
    int nodes = 1;
    int ct = 0, nzct = 0;
    vector<int> temp;
    vector<vector<int> > tree;
    for(int i = 0; i< n; ++i){
        int a;
        cin>> a;
        temp.push_back(a);
        ct++;
        
        if(a!= -1){
            nzct ++;
        }
        if(ct == nodes){
            nodes = nzct *  2;
            nzct = 0;
            ct = 0;
            tree.push_back(temp);
            temp.clear();
        }
        
    }

    
    for(int i = tree.size()-2; i> 0; --i){
        auto & nums = tree[i];
        // 每层都右旋, 每次右旋转都向下传递
        myreverse(tree, i,  k);
        // printtree(tree);

    }
    
    for(auto & nums : tree){
        for(int n : nums){
            cout<< n<< ' ';
        }
    }
    
    
    cout<< endl;
    
    return 0;
    
    

}

li54426 avatar Sep 22 '23 12:09 li54426

@li54426 大佬可以提交一个pr,在这里提交的代码无法被并入仓库 教程如下:https://www.programmercarl.com/qita/join.html

TFTree avatar Sep 25 '23 15:09 TFTree