zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

二叉树遍历 --- 原型 层次 lintcode
2023-09-14 08:58:39 时间

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

样例

给一棵二叉树 {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;
    }
};