第一题:二叉树的前、中、后序遍历
Leetcode 144.前序遍历:根、左、右
Leetcode 94.中序遍历:左、根、右
Leetcode 145.后序遍历:左、右、根
迭代遍历统一写法
// 以145 后序遍历为例
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
if (root == nullptr)
return ans;
stack<TreeNode*> mystack;
TreeNode* cur;
mystack.push(root);
while (!mystack.empty()) {
cur = mystack.top();
mystack.pop();
if (cur != nullptr) {
mystack.push(cur); // 根
mystack.push(nullptr);
if (cur->right)
mystack.push(cur->right); // 右
if (cur->left)
mystack.push(cur->left); // 左
} else {
cur = mystack.top();
mystack.pop();
ans.push_back(cur->val);
}
}
return ans;
}
};
第二题:Leetcode102. 二叉树的层序遍历
题解
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> que;
TreeNode* node;
if (root != nullptr)
que.push(root);
vector<int> level;
size_t size;
while (!que.empty()) {
level.clear();
size = que.size();
for (int i = 0; i < size; i++) {
node = que.front();
que.pop();
level.push_back(node->val);
if (node->left != nullptr)
que.push(node->left);
if (node->right != nullptr)
que.push(node->right);
}
ans.push_back(level);
}
return ans;
}
};
要点
- queue,先进先出,接口有;front(),push(),pop(),empty()
- size需要每次循环前赋值,push后会改变
第三题:Leetcode455.分发饼干(贪心算法)
题解
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int ans = 0;
for (int i = 0; i < s.size(); i++) // 饼干
{
if (ans < g.size() && g[ans] <= s[i])
ans++;
}
return ans;
}
};
要点
- 贪心思路:每次拿出最小的饼干分给饭量最小的娃
- 时间复杂度:O(nlgn),空间复杂度:O(1)