zoukankan      html  css  js  c++  java
  • 剑指offer——34之字打印二叉树

    题目描述

    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
     
    题解:
      与上道题没区别,就是在存入数据时,对于奇数行的数据,先反转一下,再存入即可
      
     1 class Solution {
     2 public:
     3     vector<vector<int> > Print(TreeNode* pRoot) {
     4         vector<vector<int>>res;
     5         BFS(pRoot, res);
     6         return res;
     7     }
     8     void BFS(TreeNode *root, vector<vector<int>>&res)
     9     {
    10         if (root == nullptr)return;
    11         queue<TreeNode*>q;
    12         q.push(root);
    13         bool fromLeft = true;
    14         while (!q.empty())
    15         {
    16             queue<TreeNode*>temp;
    17             vector<int>v;
    18             while (!q.empty())
    19             {
    20                 TreeNode* p = q.front();
    21                 q.pop();
    22                 v.push_back(p->val);
    23                 if (p->left != nullptr)temp.push(p->left);
    24                 if (p->right != nullptr)temp.push(p->right);
    25             }
    26             if(fromLeft)
    27                 res.push_back(v);
    28             else
    29             {
    30                 reverse(v.begin(), v.end());
    31                 res.push_back(v);
    32             }
    33             fromLeft = !fromLeft;
    34             q = temp;
    35         }
    36     }
    37 };
    38     
  • 相关阅读:
    页面边距设置
    事件
    Ora-00906:missing left parenthesis
    Oracle
    数据转移:把数据从一个表转到另一个表
    修改字段默认值
    数据升级包
    触发器
    复制数据库数据
    VMware vSphere Client
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11681727.html
Copyright © 2011-2022 走看看