zoukankan      html  css  js  c++  java
  • 【简单算法】29.二叉树的层次遍历

    题目:

    给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
    
    例如:
    给定二叉树: [3,9,20,null,null,15,7],
    
        3
       / 
      9  20
        /  
       15   7
    返回其层次遍历结果:
    
    [
      [3],
      [9,20],
      [15,7]
    ]

    解题思路:

    采用队列即可,按照层次依次将每层的节点入队列即可。

    /**
     * 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<vector<int>> res;
            queue<TreeNode *> qu;
            
            if(root == NULL){
                return res;
            }
            
            /*level travel*/
            qu.push(root);    
            while(!qu.empty()){
                int length = qu.size();
                vector<int> level;
                for(int i = 0;i < length;++i){
                    TreeNode * node = qu.front();
                    qu.pop();
                    level.push_back(node->val);
                    if(node->left){
                        qu.push(node->left);
                    }
                    if(node->right){
                        qu.push(node->right);
                    }
                }
                res.push_back(level);
            }
            
            return res;
        }
    };
  • 相关阅读:
    [LeetCode]Subsets II
    [LeetCode]Subsets
    [LeetCode]Combinations
    [LeetCode]Minimum Window Substring
    [LeetCode]Search a 2D Matrix
    [LeetCode]Edit Distance
    [LeetCode]Simplify Path
    Adaboost算法
    [LeetCode]Text Justification
    31、剑指offer--从1到n整数中1出现次数
  • 原文地址:https://www.cnblogs.com/mikemeng/p/8987787.html
Copyright © 2011-2022 走看看