zoukankan      html  css  js  c++  java
  • 二叉树的层次遍历

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

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

    题意:对于给定的二叉树,返回按层序遍历的结点值

    思路:利用队列,BFS

    /**
     * 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>> ans;
            queue<TreeNode *> que;
            if(!root) return ans;
            que.push(root);
            while(!que.empty()){
                vector<int> temp;  //一层地元素
                for(int i=que.size();i>0;i--) 
                {
                    TreeNode *t=que.front();
                    que.pop();
                    temp.push_back(t->val);
                    if(t->left) que.push(t->left);
                    if(t->right) que.push(t->right);
                }
                ans.push_back(temp);      //插入到ans数组中
            }
            return ans;
        }
    };
     
  • 相关阅读:
    在CentOS7上搭建MySQL主从复制与读写分离
    数据库 引擎
    数据库 事务
    数据库 索引
    MYSQL
    基于mysqld_multi实现MySQL 5.7.24多实例多进程配置
    09 引导过程与故障修复
    chapter 8.3
    作业 8.1
    Chapter 04 作业
  • 原文地址:https://www.cnblogs.com/Bipolard/p/9996967.html
Copyright © 2011-2022 走看看