面试题32 - I. 从上到下打印二叉树
广搜,将每一层存入队列,然后输出即可
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
vector<int>ans;
queue<TreeNode*>q;
if(root==NULL) return ans;
q.push(root);
while(!q.empty()){
root = q.front();
q.pop();
int m=root->val;
ans.push_back(m);
if(root->left!=NULL) q.push(root->left);
if(root->right!=NULL) q.push(root->right);
}
return ans;
}
};
剑指 Offer 32 - II. 从上到下打印二叉树 II
广搜,同时入队的结点一定是同一层的,因此在每一次出队时,判断当前队列长度,将这一部分的同时出队,出队的元素即为同一层的
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>>ans;
queue<TreeNode*>q;
if(root==NULL) return ans;
q.push({root});
while(!q.empty()){
int col=q.size();
vector<int>v;
for(int i=0;i<col;i++){
TreeNode* node=q.front();
q.pop();
v.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
ans.push_back(v);
}
return ans;
}
};
剑指 Offer 32 - III. 从上到下打印二叉树 III
广搜,与上一题一致,在最后多加一个reverse即可
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>>ans;
queue<TreeNode*>q;
if(root==NULL) return ans;
q.push({root});
while(!q.empty()){
int col=q.size();
vector<int>v;
for(int i=0;i<col;i++){
TreeNode* node=q.front();
q.pop();
v.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
ans.push_back(v);
}
for(int i=1;i<ans.size();i+=2) reverse(ans[i].begin(),ans[i].end());
return ans;
}
};