剑指 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:
queue<TreeNode*> q;
vector<int> levelOrder(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
q.push(root);
while(!q.empty())
{
TreeNode* cur = q.front();
q.pop();
res.push_back(cur->val);
if(cur->left!=NULL) q.push(cur->left);
if(cur->right!=NULL) q.push(cur->right);
}
return res;
}
};
剑指 Offer 32 - II. 从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
注意:
1.判断是否为空树
2.for循环内的第二个不能写成q.size().
/**
* 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==NULL) return res;
q.push(root);
while(!q.empty())
{
vector<int> row;
int k = q.size();
for(int i = 0;i < k;i++)
{
TreeNode* cur = q.front();
q.pop();
row.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
res.push_back(row);
}
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<vector<int>> res;
queue<TreeNode*> q;
if(root==NULL) return res;
q.push(root);
int ac = 1;
while(!q.empty())
{
vector<int> row;
int k = q.size();
for(int i = 0;i < k;i++)
{
TreeNode* cur = q.front();
q.pop();
row.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
ac++;
if(ac%2==1) reverse(row.begin(),row.end());
res.push_back(row);
}
return res;
}
};