二叉树的层次遍历

来源:互联网 发布:linux tee 用法 编辑:程序博客网 时间:2024/06/07 10:38
样例
给一棵二叉树 {3,9,20,#,#,15,7} :


  3
 / \
9  20
  /  \
 15   7
返回他的分层遍历结果:


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

]

class Solution {  

    /**  
     * @param root : The root of binary tree.  
     * @return : buttom-up level order a list of lists of integer  
     */  
public:
    vector<vector<int> > levelOrder(TreeNode *root) {
        // write your code here
        vector<vector<int> > vec;
        if(root==NULL)
              return vec;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        vector<int> it;
        while(!q.empty())
        {
            TreeNode* p = q.front();
            q.pop();
            if(p!=NULL)
           {
               it.push_back(p->val);
               if(p->left!=NULL) 
               q.push(p->left);
               if(p->right!=NULL)
               q.push(p->right);
           }
           else
           {
               if(!it.empty())
               {
                   vec.push_back(it);
                   it.clear();
                   q.push(NULL);




               }




           }




        }
       return vec;




     }




   };
0 0