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

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

 

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

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

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

提示:

节点总数 <= 1000
注意:本题与主站 102 题相同:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

通过次数1,363提交次数1,914

 

做过,不说了

#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) {

        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){
                samedeep = m_queue.size();
                m_res.push_back(m_temp);
                m_temp.clear();
            }

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

 

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