zoukankan      html  css  js  c++  java
  • LeetCode: Populating Next Right Pointers in Each Node II

    这题关键是要记录下一层第一个节点

     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     TreeLinkNode *nextright(TreeLinkNode *root) {
    12         while (root) {
    13             if (root->left) return root->left;
    14             if (root->right) return root->right;
    15             root = root->next;
    16         }
    17         return NULL;
    18     }
    19     void connect(TreeLinkNode *root) {
    20         if (!root) return;
    21         TreeLinkNode *second, *first;
    22         first = root;
    23         second = NULL;
    24         first->next = NULL;
    25         while (first) {
    26             if (first->left) {
    27                 if (!second) second = first->left;
    28                 if (first->right) first->left->next = first->right;
    29                 else first->left->next = nextright(first->next);
    30             }
    31             if (first->right) {
    32                 if (!second) second = first->right;
    33                 first->right->next = nextright(first->next);
    34             }
    35             first = first->next;
    36             if (!first) {
    37                 first = second;
    38                 second = NULL;
    39             }
    40         }
    41     }
    42 };

     如果可以用extra space,可以用下面这段代码

     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         queue<TreeLinkNode *> S;
    13         if (!root) return;
    14         S.push(root);
    15         S.push(NULL);
    16         while (!S.empty()) {
    17             TreeLinkNode *front = S.front();
    18             S.pop();
    19             if (!front) continue;
    20             front->next = S.front();
    21             if (front->left) S.push(front->left);
    22             if (front->right) S.push(front->right);
    23             if (!S.front()) S.push(NULL);
    24         }
    25     }
    26 };
  • 相关阅读:
    题解-bzoj1283序列 & bzoj4842 [Neerc2016]Delight for a Cat
    题解-bzoj4061 CERC-2012Farm and Factory
    题解-bzoj3569 DZY Loves Chinese II
    题解-bzoj3901 棋盘游戏
    题解-PKUWC2018 Minimax
    题解-PKUWC2018 Slay the Spire
    题解-PKUWC2018 随机算法
    题解-PKUWC2018 随机游走
    bzoj1010[HNOI2008]玩具装箱toy 斜率优化dp
    bzoj1096[ZJOI2007]仓库建设 斜率优化dp
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3030723.html
Copyright © 2011-2022 走看看