# 【剑指Offer】搜索与回溯算法

36 篇文章 0 订阅

#### 剑指 Offer 32 - I. 从上到下打印二叉树

    3
/ \
9  20
/  \
15   7


[3,9,20,15,7]


1. 节点总数 <= 1000
/**
* 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) {
queue<TreeNode*> q;
vector<int> ans;
if(root == nullptr)return ans;
q.push(root);
while(q.empty() == false){
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);
}
return ans;
}
};


#### 剑指 Offer 32 - II. 从上到下打印二叉树 II

    3
/ \
9  20
/  \
15   7


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


1. 节点总数 <= 1000
/**
* 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>> ans;
queue<TreeNode*> q;
if(root == nullptr)return ans;
q.push(root);
int i = 0;
while(q.empty() == false){
ans.push_back({});
for(int j = q.size(); j > 0; -- j){
TreeNode *node = q.front();
q.pop();
ans[i].push_back(node->val);
if(node->left != nullptr)q.push(node->left);
if(node->right != nullptr)q.push(node->right);
}
i ++;
}
return ans;
}
};


#### 剑指 Offer 32 - III. 从上到下打印二叉树 III

    3
/ \
9  20
/  \
15   7


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


1. 节点总数 <= 1000
/**
* 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>> ans;
queue<TreeNode*> q;
if(root == nullptr)return ans;
q.push(root);
int i = 0;
bool tag = false;
while(q.empty() == false){
ans.push_back({});
stack<int> stac;
for(int j = q.size(); j > 0; -- j){
TreeNode *node = q.front();
q.pop();
if(tag){
stac.push(node->val);
}else{
ans[i].push_back(node->val);
}
if(node->left != nullptr)q.push(node->left);
if(node->right != nullptr)q.push(node->right);
}
while(stac.empty() == false){
ans[i].push_back(stac.top());
stac.pop();
}
tag = !tag;
i ++;
}
return ans;
}
};


• 1
点赞
• 1
收藏
• 打赏
• 0
评论
10-15 325
04-25 129
02-06 290

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

Ryu眼神不太好

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。