Lintcode---二叉树的层次遍历(原型)

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

样例

给一棵二叉树 {3,9,20,#,#,15,7} :

  3
 / \
9  20
  /  \
 15   7

返回他的分层遍历结果:

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

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 
 
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: 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*> que;
        que.push(root);
        
        while(!que.empty()){
            int count=que.size();
            vector<int> vec_temp;
            
            while(count--){
                TreeNode* temp=que.front();
                que.pop();
                
                vec_temp.push_back(temp->val);
                
                if(temp->left){
                    que.push(temp->left);
                }
                
                if(temp->right){
                    que.push(temp->right);
                }
            }
            
            vec.push_back(vec_temp);
        }
        
        return vec;
    }
};

 

posted @ 2017-07-03 14:16  静悟生慧  阅读(800)  评论(0编辑  收藏  举报