• 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 };
  • 相关阅读:
    epoll 实现回射服务器
    select函数的介绍和使用
    期末项目需求分析报告
    Spring AOP Capabilities and Goals
    Domain Logic approaches
    Lamda Expression
    CDI furture
    23种设计模式
    connector for python
    Spring reference
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3030704.html
Copyright © 2020-2023  润新知