LeetCode- 面试题32 - III. 从上到下打印二叉树 III

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

 

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [20,9],
  [15,7]
]

 

提示:

  1. 节点总数 <= 1000

通过次数1,009提交次数1,646

 

前面得题,改一点点

 

#include 
#include 
#include 
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector> levelOrder(TreeNode* root) {

        deep_count = 0;
        if(root){
            m_queue.push(root);
        }

        int samedeep =m_queue.size();

        while(!m_queue.empty()){
            TreeNode *front = m_queue.front();
            m_temp.push_back(front->val);
            m_queue.pop();
            samedeep--;

            if(front->left){
                m_queue.push(front->left);
            }
            if(front->right){
                m_queue.push(front->right);
            }

            if(samedeep==0){
                deep_count++;
                samedeep = m_queue.size();
                if(deep_count%2==0){
                    reverse(m_temp.begin(),m_temp.end());
                }
                m_res.push_back(m_temp);
                m_temp.clear();
            }

        }
        return m_res;
    }
private:
    int deep_count;
    vector m_temp;
    vector> m_res;
    queuem_queue;
};

 

你可能感兴趣的:(算法,C++,LeetCode)