今天做了两题,是同一个系列,都是打印二叉树中的值,不同之处在于一个分层一个不分层。很典型的BFS的解法。
关键点基本上是两点:
- 边界条件的检测,即:root为空时返回空的vector;
- 使用队列
queue
存储节点,当队列为空时,说明遍历完毕。
(此处顺便复习一下queue
最基本的用法:
queue<int> q;
q.push(3); // q = [3]
q.push(5); // q = [3, 5]
int val = q.front(); // val = 3
q.pop(); // q = [5];
(题目为剑指offer 32 Ⅰ、Ⅱ,题目内容不再赘述,下边直接贴代码)
Ⅰ
/**
* 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:
vector<int> levelOrder(TreeNode* root) {
if (root == nullptr) {
return {};
}
vector<int> temp;
queue<TreeNode*> nodes;
TreeNode* node;
nodes.push(root);
while (!nodes.empty()) {
node = nodes.front();
nodes.pop();
temp.push_back(node->val);
if (node->left) {
nodes.push(node->left);
}
if (node->right) {
nodes.push(node->right);
}
}
return temp;
}
};
Ⅱ
/**
* 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:
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr) {
return {{}};
}
vector<vector<int>> res;
queue<TreeNode*> nodes;
TreeNode* node;
nodes.push(root);
while (!nodes.empty()) {
int size = nodes.size();
vector<int> temp;
// for (int i = 0; i < size; ++i) {
while (!nodes.empty()) {
node = nodes.front();
temp.push_back(node->val);
nodes.pop();
}
res.push_back(temp);
temp.clear();
if (node->left) {
nodes.push(node->left);
}
if (node->right) {
nodes.push(node->right);
}
}
return res;
}
};
网友评论