剑指 Offer 32 - III. 从上到下打印二叉树 III
题目链接
剑指 Offer 32 - III. 从上到下打印二叉树 III
思路分析
代码实现
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
bool flag = true;
vector<vector<int>> ret;
queue<TreeNode*> q;
if(root != NULL)
q.push(root);
while(!q.empty())
{
int sz = q.size();
vector<int> path;
for(int i = 0; i < sz; ++i)
{
TreeNode* node = q.front();
path.push_back(node->val);
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
if(!flag)
{
reverse(path.begin(), path.end());
}
flag = !flag;
ret.push_back(path);
}
return ret;
}
};
|