目录
剑指 Offer 32 - I. 从上到下打印二叉树
题目
代码
/**
* 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) {
//层序遍历,使用队列
vector<int> res;
queue<TreeNode*> q;
if(root != nullptr) {
q.push(root);
}
while(!q.empty()) {
int sz = q.size();
for(int i = 0; i < sz; i++) {
TreeNode* node = q.front();
q.pop();
res.push_back(node->val);
if(node->left != nullptr) {
q.push(node->left);
}
if(node->right != nullptr) {
q.push(node->right);
}
}
}
return res;
}
};
剑指 Offer 32 - II. 从上到下打印二叉树 II
题目
代码
/**
* 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) {
//每层打印一行
vector<vector<int>> res;
queue<TreeNode*>q;
if(root != nullptr) {
q.push(root);
}
while(!q.empty()) {
int sz = q.size();
vector<int> ans;
for(int i = 0;i < sz;i++) {
TreeNode* node = q.front();
q.pop();
ans.push_back(node->val);
if(node->left != nullptr) {
q.push(node->left);
}
if(node->right != nullptr){
q.push(node->right);
}
}
res.push_back(ans);
}
return res;
}
};
剑指 Offer 32 - III. 从上到下打印二叉树 III
题目
代码
/**
* 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) {
//一行从左到右,一行从右到左
//vector可以reverse
vector<vector<int>> res;
queue<TreeNode*>q;
bool isreverse = true;
if(root != nullptr) {
q.push(root);
}
while(!q.empty()) {
int sz = q.size();
vector<int> ans;
for(int i = 0; i < sz; i++) {
TreeNode* node = q.front();
q.pop();
ans.push_back(node->val);
if(node->left != nullptr) {
q.push(node->left);
}
if(node->right != nullptr) {
q.push(node->right);
}
}
//判断何时ans反转
if(isreverse == false) {
reverse(ans.begin(),ans.end());
isreverse = true;
}else {
isreverse = false;
}
res.push_back(ans);
}
return res;
}
};