您的位置:首页 > 其它

leetcode简单题目两道(4)

2017-04-22 22:08 387 查看
心情还是有问题,保持每日更新,只能如此了。

Problem

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Example:

Given binary tree {3,9,20,#,#,15,7},

····3
/ \
9  20
/  \
15   7
Result

return its level order traversal as:

[
[3],
[9,20],
[15,7]
]
Code

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int HeightOfTree(TreeNode* root) {
int result = 0;
if (root == NULL) {
return result;
}
int left = HeightOfTree(root->left) + 1;
int right = HeightOfTree(root->right) + 1;
result = left > right ? left : right;
return result;
}
void calLevelOrder(TreeNode* root, int level, vector<vector<int> >& result) {
if (root == NULL) {
return;
}
result[level].push_back(root->val);
calLevelOrder(root->left, level + 1, result);
calLevelOrder(root->right, level + 1, result);
}
vector<vector<int> > levelOrder(TreeNode* root) {
vector<vector<int> > result;
vector<int> v;
if (root == NULL) {
return result;
}
int height = HeightOfTree(root);
for (int i = 0; i < height; i++) {
result.push_back(v);
}
calLevelOrder(root, 0, result);
return result;
}
};


Problem1

Write a function that takes a string as input and returns the string reversed.

Example:

Given s = "hello", return "olleh".

Code

class Solution {
public:
string reverseString(string s) {
if (s.size() <= 1) {
return s;
}
int i = 0, j = s.size() - 1;
char ch;
while (i < j) {
ch = s[i];
s[i] = s[j];
s[j] = ch;
i++;
j--;
}
return s;
}
};
Problem2

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Given s = "hello", return "holle".

Example 2:

Given s = "leetcode", return "leotcede".

Code

class Solution {
public:
string reverseVowels(string s) {
if (s.size() <= 1) {
return s;
}
int i = 0, j = s.size() - 1;
char ch;
while (i < j) {
while(i < j && s[i] != 'a' && s[i] != 'e' && s[i] != 'i' && s[i] != 'o' && s[i] != 'u'
&& s[i] != 'A' && s[i] != 'E' && s[i] != 'I' && s[i] != 'O' && s[i] != 'U') {
i++;
}
while(i < j && s[j] != 'a' && s[j] != 'e' && s[j] != 'i' && s[j] != 'o' && s[j] != 'u'
&& s[j] != 'A' && s[j] != 'E' && s[j] != 'I' && s[j] != 'O' && s[j] != 'U') {
j--;
}
ch = s[i];
s[i] = s[j];
s[j] = ch;
i++;
j--;
}
return s;
}
};
说明

与上面同样的逻辑,只是出现特定的字符才交换位置


PS:存货快用完了。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: