题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

在层次遍历上的一个简单应用

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
      //  这道题观察就可以发现,在层次遍历的基础上
      //  奇数层不用翻转,偶数层翻转即可
    vector<vector<int> > Print(TreeNode* pRoot) {
        //  翻转序列的标志
      int flag = 1; 
      std::queue<TreeNode *> queue_;
      std::vector<std::vector<int>> res;
      
      if (pRoot == nullptr) {
        return res;
      }
      
      queue_.push(pRoot);
      
      while (!queue_.empty()) {
        int size = queue_.size();
        std::vector<int> tmp;
        
        for (int i = 0; i < size; ++i) {
          TreeNode *ptr = queue_.front();
          queue_.pop();
          tmp.push_back(ptr->val);
          if (ptr->left) {
            queue_.push(ptr->left);
          }
          if (ptr->right) {
            queue_.push(ptr->right);
          }
        }
        
        if (flag % 2 == 0) {
          reverse(tmp.begin(), tmp.end());
        }
        
        ++flag;
        res.emplace_back(std::move(tmp));
      }
      
      return res;
    }
    
};
全部评论

相关推荐

生命诚可贵:先不说内容怎么样 排版就已经太差劲了 第一眼看不到重点,第二眼已经没有再看的耐心了, 篇幅占的太满了 字体不要用灰色 观感不好 想重点突出的黑色加粗就可以了 多列要点 少些大段的句子 项目经历把项目用的技术要点列出来,光写个python plc什么的太宽泛了 自我评价也有点偏多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务