剑指 Offer 32 - I. 从上到下打印二叉树
思路:建立队列q用来存放每个节点的指针,一个数组ans用来存放最后的答案,插入根节点之后,当队列不为空时,用n存放队列的长度,其实也就是每一层节点的个数,每次取出队首存放到ans中,接着出队,将其子节点的指针(不为空)存放在队列中,接着改变n的值,队首出队,接着插入其队首的子节点,重复操作。
代码:
/**
* 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>ans;
queue<TreeNode*>q;
if(root!=NULL)
q.push(root);
while(!q.empty())
{
int n=q.size();
for(int i=0;i<n;i++)
{
TreeNode* t=q.front();
q.pop();
ans.push_back(t->val);
if(t->left!=NULL) q.push(t->left);
if(t->right!=NULL) q.push(t->right);
}
}
return ans;
}
};
剑指 Offer 32 - II. 从上到下打印二叉树 II
思路:与上一题的不同之处就在于这题它分层存储,所以增加一个m数组用来存储每一层的节点值,然后ans数组在分别存储每一层的答案。
代码:
/**
* 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!=NULL)
q.push(root);
while(!q.empty())
{
int n=q.size();
vector<int> m;
for(int i=0;i<n;i++)
{
TreeNode* t=q.front();
q.pop();
m.push_back(t->val);
if(t->left!=NULL) q.push(t->left);
if(t->right!=NULL) q.push(t->right);
}
ans.push_back(m);
}
return ans;
}
};
剑指 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<vector<int> >ans;
queue<TreeNode*> q;
if(root!=NULL)
q.push(root);
int k=1;
while(!q.empty())
{
vector<int>m;
int n=q.size();
for(int i=0;i<n;i++)
{
TreeNode* t=q.front();
m.push_back(t->val);
q.pop();
if(t->left!=NULL) q.push(t->left);
if(t->right!=NULL) q.push(t->right);
}
if(k%2==0)
{
reverse(m.begin(),m.end());
}
k++;
ans.push_back(m);
}
return ans;
}
};