leetcode笔记-层序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * }
 */
class Solution {
public:
     vector<vector<int>> levelOrder(TreeNode* root) {
        vector<int> a;
        vector<vector<int>> b;
        queue<TreeNode*> s;
        s.push(root);
        int level=1;
        if(root==NULL) return b;
        else 
        {
            
            while(!s.empty())
            {
               TreeNode *cur;
               queue<TreeNode *> nxtlevel;
               while(!s.empty())
                {
                    TreeNode *cur=s.front();
                    s.pop();
                    a.push_back(cur->val);
                    if(cur->left!=NULL) nxtlevel.push(cur->left);
                    if(cur->right!=NULL) nxtlevel.push(cur->right);
                    
                }
                b.push_back(a);
                s=nxtlevel; 
                a.clear(); 
                
            } 
            return b; 
            
        } 
        
    }
     
 };

你可能感兴趣的:(leetcode笔记-层序遍历)