/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param k int整型
* @return TreeNode类
*/
TreeNode* cyclicShiftTree(TreeNode* root, int k) {
// write code here
if(!root){
return nullptr;
}
queue<TreeNode*> cur_level;
cur_level.push(root);
vector<TreeNode*> level;
level.emplace_back(root);
tree.emplace_back(level);
level.clear();
while(!cur_level.empty())
{
TreeNode *cur_node=cur_level.front();
cur_level.pop();
if(cur_node)
{
if(cur_node->left)
{
level.push_back(cur_node->left);
}
if(cur_node->right)
{
level.push_back(cur_node->right);
}
}
if(cur_level.empty())
{
tree.emplace_back(level);
for(int i=0;i<level.size();i++)
{
cur_level.push(level[i]);
}
level.clear();
}
}
int deepth=tree.size();
for(int i=deepth-2;i>=0;i--)
{
int len=tree[i].size();
level=vector<TreeNode*>(len*2,nullptr);
for(int j=0;j<len;j++)
{
if(tree[i][j]->left)
{
level[((j*2)+k)%(len*2)]=tree[i][j]->left;
}
if(tree[i][j]->right)
{
level[((j*2+1)+k)%(len*2)]=tree[i][j]->right;
}
}
for(int j=0;j<len;j++)
{
tree[i][j]->left=level[j*2];
tree[i][j]->right=level[j*2+1];
}
}
return root;
}
private:
vector<vector<TreeNode*>> tree;
};
层序遍历,把树存到二维数组里面,然后模拟右移就行了。

京公网安备 11010502036488号