• 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 };
  • 相关阅读:
    rustlang入门教程
    中间件日志切割
    Redis非关系型缓存数据库集群部署、参数、命令工具
    SaltStack自动化软件简介及安装
    CentOS根目录下各目录介绍
    Dockerfile书写介绍及构建ssh镜像、tomcat镜像、nginx镜像
    DockerFile执行报错解决
    阿里云CentOS7.2把默认语言修改成中文
    JavaScript 如何判断一个数据的类型
    MongoDB windows 下安装配置
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3030723.html
Copyright © 2020-2023  润新知