zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    static 续--
    [非原创]java 中static作用解析
    public/private/protected作用域
    三种排序方法(冒泡、选择、插入)
    SQLMAP自动注入(四)
    SQLMAP自动注入(三)—Injection,Detection,Techniques
    SQLMAP自动注入(二)-request,优化
    SQLMAP自动注入(一)
    SQL盲注
    SQL注入——猜测字段名称
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3030704.html
Copyright © 2011-2022 走看看