zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

    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]
    ]

    解题思路:

    广度优先遍历。

    代码:

     1 /**
     2  * Definition for binary tree
     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<vector<int>> ans;
    14         if (root == NULL) return ans;
    15 
    16         queue<TreeNode *> one, another;
    17         one.push(root);
    18 
    19         while (!one.empty() || !another.empty()) {
    20             if (!one.empty()) {
    21                 vector<int> cur_ans;
    22                 while (!one.empty()) {
    23                     TreeNode * node = one.front();
    24                     cur_ans.push_back(node->val);
    25                     if (node->left != NULL) another.push(node->left);
    26                     if (node->right != NULL) another.push(node->right);
    27                     one.pop();
    28                 }
    29                 ans.push_back(cur_ans);
    30             }
    31             if (!another.empty()) {
    32                 vector<int> cur_ans;
    33                 while (!another.empty()) {
    34                     TreeNode *node = another.front();
    35                     cur_ans.push_back(node->val);
    36                     if (node->left != NULL) one.push(node->left);
    37                     if (node->right != NULL) one.push(node->right);
    38                     another.pop();
    39                 }
    40                 ans.push_back(cur_ans);
    41             }
    42         }
    43         return ans;
    44     }
    45 };
  • 相关阅读:
    告知服务器意图的HTTP方法
    初识HTTP协议
    与HTTP关系密切的三个协议:IP,TCP,DNS
    TCP/IP的分层管理
    CSS position 详解
    ASP.NET MVC的 ActionResult跳转视图方法
    html js打印
    C# 跳出循环几种方法详解
    c# 下载文件封装方法
    c# MVC @Styles.Render @Scripts.Render 使用方法
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728266.html
Copyright © 2011-2022 走看看