剑指 Offer 32 从上到下打印二叉树IIIIII
Posted Billy Miracle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指 Offer 32 从上到下打印二叉树IIIIII相关的知识,希望对你有一定的参考价值。
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> result;
queue<TreeNode*> que;
if(root != NULL)
que.push(root);
while(!que.empty())
int size = que.size();
for(int i = 0; i < size; i++)
TreeNode* node = que.front();
que.pop();
result.push_back(node->val);
if(node->left != NULL)
que.push(node->left);
if(node->right != NULL)
que.push(node->right);
return result;
;
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>> result;
queue<TreeNode *> que;
if (root)
que.push(root);
while (que.size())
vector<int> row;
int size = que.size();
//记录下这一层有几个
for (int i = 0; i < size; ++i)
//针对每层的节点数分层操作
TreeNode *node = que.front();
que.pop();
row.push_back(node->val);
if (node->left)
que.push(node->left);
if (node->right)
que.push(node->right);
result.push_back(row);
return result;
;
III
菜鸡思路:
虽然还是层次遍历、分层返回,但是要求的是要针对性的对一些层倒序,直接在上一题代码改造,判断一下是第几层,偶数层则数组倒序。只比上一题多了一个if
条件块。
菜鸡代码:
/**
* 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>> result;
queue<TreeNode *> que;
if (root)
que.push(root);
while (que.size())
vector<int> row;
int size = que.size();
for (int i = 0; i < size; ++i)
TreeNode *node = que.front();
que.pop();
row.push_back(node->val);
if (node->left)
que.push(node->left);
if (node->right)
que.push(node->right);
if (result.size() % 2)
reverse(row.begin(), row.end());
result.push_back(row);
return result;
;
创作打卡挑战赛
赢取流量/现金/CSDN周边激励大奖
以上是关于剑指 Offer 32 从上到下打印二叉树IIIIII的主要内容,如果未能解决你的问题,请参考以下文章