- leetcode226-翻转二叉树
题型:树、递归
难度:简单
题目:翻转一棵二叉树。
代码:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==nullptr)
return root;
TreeNode *pLeft = invertTree(root->left);
TreeNode *pRight = invertTree(root->right);
root->left = pRight;
root->right = pLeft;
return root;
}
};
- leetcode151-翻转字符串里的单词
题型:字符串
难度:中等
题目:给定一个字符串,逐个翻转字符串中的每个单词。
代码:
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(),s.end());
int len = s.size();
int i = 0;
int end = 0;
int index = 0;
for(i=0;i<len;i++)
{
if(s[i] == ' ')
continue;
if(index != 0)
s[index++] = ' ';
end = i;
while(end<len && s[end]!=' ')
s[index++] = s[end++];
int strsize = end-i;
reverse(s.begin()+index-strsize,s.begin()+index);
i = end;
}
s.erase(s.begin()+index,s.end());
return s;
}
};