• LeetCode: Populating Next Right Pointers in Each Node


    思路对的,少数次过,基本一次过吧

     1 /**
     2  * Definition for binary tree with next pointer.
     3  * struct TreeLinkNode {
     4  *  int val;
     5  *  TreeLinkNode *left, *right, *next;
     6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void connect(TreeLinkNode *root) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         queue<TreeLinkNode *> S;
    15         queue<TreeLinkNode *> T;
    16         if (!root) return;
    17         S.push(root);
    18         while (!S.empty()) {
    19             TreeLinkNode *tmp = S.front();
    20             S.pop();
    21             if (tmp->left || tmp->right) {
    22                 T.push(tmp->left);
    23                 T.push(tmp->right);
    24             }
    25             if (!S.empty()) tmp->next = S.front();
    26             else tmp->next = NULL;
    27             if (S.empty()) {
    28                 while (!T.empty()) {
    29                     S.push(T.front());
    30                     T.pop();
    31                 }
    32             }
    33         }
    34     }
    35 };

     贴一段后来写的更加好的代码

     1 /**
     2  * Definition for binary tree with next pointer.
     3  * struct TreeLinkNode {
     4  *  int val;
     5  *  TreeLinkNode *left, *right, *next;
     6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void connect(TreeLinkNode *root) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (!root) return;
    15         queue<TreeLinkNode*> S, T;
    16         S.push(root);
    17         while (!S.empty()) {
    18             while (!S.empty()) {
    19                 TreeLinkNode *tmp = S.front();
    20                 S.pop();
    21                 if (tmp->left) T.push(tmp->left);
    22                 if (tmp->right) T.push(tmp->right);
    23                 tmp->next = S.empty()? NULL : S.front();
    24             }
    25             S.swap(T);
    26         }
    27     }
    28 };
  • 相关阅读:
    LR常用函数汇总
    常用工具软件包下载地址
    MySQL分表操作的例子
    Redis性能优化之redis.cnf配置参数
    Redis监控之redis-live.conf配置
    Oracle中查询和定位数据库问题的SQL语句
    Oracle种常用性能监控SQL语句
    show processlist使用介绍
    MySQL流程控制和存储过程介绍
    MySQL字符集和排序介绍
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3030704.html
Copyright © 2020-2023  润新知