6.Z字型变换
leetcode 6 中等

解题思路:
遍历一遍字符串,从左到右按箭头方向迭代 s ,将每个字符添加到合适的行。之后从上到下遍历行即可。当前行 curRow 为 0 或 n-1 时,箭头发生反向转折。
class Solution {
public:
string convert(string s, int numRows) {
if(numRows<2) return s;
bool flag=false;
int len=s.size();
//// 防止s的长度小于行数
vector<string>nrows(min(numRows,len));
int curRow=0;
for(int i=0;i<len;i++){
nrows[curRow]+=s[i];
//当前行curRow为0或numRows -1时,箭头发生反向转折
if(curRow==0||curRow==numRows-1){
flag=!flag;//状态反转
}
curRow+=flag?1:-1;//在最上面或者最下面要开始相减,中间则是加加
}
string ret;
// 从上到下遍历行
for(int i=0;i<numRows;i++){
ret+=nrows[i];
}
return ret;
}
};
114.二叉树展开为链表
leetcode144

解题思路:
解法1:先将左子树和右子树分别展开为链表,然后把左子树接到根的右子树上,用一个临时变量储存当前的右子树,遍历右子树找到最后一个节点,把临时变量接到后面即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(root==nullptr) return ;
if(root->left) flatten(root->left);
if(root->right) flatten(root->right);
TreeNode *tmp=root->right;
root->right=root->left;
root->left=nullptr;
while(root->right){
root=root->right;
}
root->right=tmp;
}
};
解法2:用前序遍历,将结点储存进入一个容器vector中,然后将他们串起来即可;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*>ans;
void preorder(TreeNode *root){
if(root){
ans.push_back(root);
preorder(root->left);
preorder(root->right);
}
}
void flatten(TreeNode* root) {
if(root==nullptr) return ;
preorder(root);
int len=ans.size();
for(int i=1;i<len;i++){
TreeNode *pre=ans[i-1],*cur=ans[i];
pre->right=cur;
pre->left=nullptr;
}
}
};
187

被折叠的 条评论
为什么被折叠?



