zoukankan      html  css  js  c++  java
  • Leetcode 102. Binary Tree Level Order Traversal

    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,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

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

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    OJ's Binary Tree Serialization:

    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

    Here's an example:

       1
      / 
     2   3
        /
       4
        
         5
    

    The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

    分析:二叉树的层序遍历,使用广度优先搜索,建立一个队列q。
    每次将队首temp结点出队列的同时,将temp的左孩子和右孩子入队
    用size标记入队后的队列长度
    row数组始终为当前层的遍历结果,然后用while(size–)语句保证每一次保存入row的只有一层。
    每一次一层遍历完成后,将该row的结果存入二维数组v。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int>> levelOrder(TreeNode* root) {
    13         vector<int> row;
    14         vector<vector<int>> v;
    15         queue<TreeNode *> q;
    16         if(root == NULL)
    17             return v;
    18         q.push(root);
    19         TreeNode *temp;
    20         while(!q.empty()) {
    21             int size = q.size();
    22             while(size--) {
    23                 temp = q.front();
    24                 q.pop();
    25                 row.push_back(temp->val);
    26                 if(temp->left != NULL) {
    27                     q.push(temp->left);
    28                 }
    29                 if(temp->right != NULL) {
    30                     q.push(temp->right);
    31                 }
    32             }
    33             v.push_back(row);
    34             row.clear();
    35         }
    36         return v;
    37     }
    38 };
    View Code
  • 相关阅读:
    selenium的持续问题解决
    为什么使用Nginx
    [转]性能测试场景设计深度解析
    [转]CentOS7修改时区的正确姿势
    [转]利用Fiddler模拟恶劣网络环境
    [转]什么是微服务
    [转] WebSocket 教程
    [转] Python实现简单的Web服务器
    shell修改配置文件参数
    [转] linux shell 字符串操作(长度,查找,替换)详解
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5503422.html
Copyright © 2011-2022 走看看