zoukankan      html  css  js  c++  java
  • LeetCode--Binary Tree Level Order Traversal

    用两个队列实现,交叉使用,达到判断层的目的

     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> > res;
    14         if(root == NULL)
    15         {
    16             return res;
    17         }
    18         queue<TreeNode *> q1;
    19         queue<TreeNode *> q2;
    20         q1.push(root);
    21         while(!q1.empty() || !q2.empty())
    22         {
    23             vector<int> tmpres;
    24             if(!q1.empty())
    25             {
    26                 while(!q1.empty())
    27                 {
    28                     TreeNode *tmp = q1.front();
    29                     q1.pop();
    30                     tmpres.push_back(tmp->val);
    31                     if(tmp->left!=NULL)
    32                     {
    33                         q2.push(tmp->left);
    34                     }
    35                     if(tmp->right!=NULL)
    36                     {
    37                         q2.push(tmp->right);
    38                     }
    39                 }
    40             }
    41             else
    42             {
    43                 while(!q2.empty())
    44                 {
    45                     TreeNode *tmp = q2.front();
    46                     q2.pop();
    47                     tmpres.push_back(tmp->val);
    48                     if(tmp->left!=NULL)
    49                     {
    50                         q1.push(tmp->left);
    51                     }
    52                     if(tmp->right!=NULL)
    53                     {
    54                         q1.push(tmp->right);
    55                     }
    56                 }
    57             }
    58             res.push_back(tmpres);
    59         }
    60         return res;
    61     }
    62 };
  • 相关阅读:
    sigpending
    js 动态计算折扣后总价格
    让ie6支持fixed最简单和实用的方法
    jquery提示气泡
    在线API,桌面版,jquery,css,Android中文开发文档,JScript,SQL掌用实例
    三元组表
    B-树
    二叉排序树
    顺序查找
    二分查找
  • 原文地址:https://www.cnblogs.com/cane/p/3959940.html
Copyright © 2011-2022 走看看