解题思路
1.首先建一棵树,树节点中用bool存储当前的状态,用一个int存储当前节点的编号
2.多次前序遍历树,每次遍历时修改bool值,
C++ 代码
#include <iostream>
#include <cmath>
using namespace std;
int n;
int nth;
int res;
struct TreeNode{
bool val;
int k;
TreeNode* left;
TreeNode* right;
TreeNode(bool _val, int _k):val(_val),k(_k), left(NULL),right(NULL){};
};
void buildtree(TreeNode* root){
if((root->k)*2<=(pow(2,n)-1)){
root->left = new TreeNode(false, 2*(root->k));
buildtree(root->left);
}
if(((root->k)*2+1)<=(pow(2,n)-1)){
root->right = new TreeNode(false, 2*(root->k)+1);
buildtree(root->right);
}
}
void trave_tree(TreeNode* _root){
if(!_root)return;
res = _root->k;
if(_root->val){
_root->val = false;
trave_tree(_root->right);
}
else if(!_root->val){
_root->val = true;
trave_tree(_root->left);
}
}
int main(){
cin >> n;
cin >> nth;
TreeNode* root = new TreeNode(false, 1);
buildtree(root);
for(int i = 0; i < nth; i++){
trave_tree(root);
}
cout << res;
return 0;
}