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 };
  • 相关阅读:
    Kooboo CMS
    Kooboo CMS
    Kooboo CMS
    Kooboo CMS
    Kooboo CMS
    Ajax.BeginForm VS Html.BeginForm
    ASP.NET或者 js方式实现文件夹多图片浏览的方式
    C++入门知识总结(1)
    几个步骤轻松搞定ASP.NET 依赖注入。
    使用GIT@OSChina 实现协同工作的方法。
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728266.html
Copyright © 2011-2022 走看看