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

    Follow up for problem "Populating Next Right Pointers in Each Node".

    What if the given tree could be any binary tree? Would your previous solution still work?

    Note:

    • You may only use constant extra space.

    For example,
    Given the following binary tree,

             1
           /  \
          2    3
         / \    \
        4   5    7
    

    After calling your function, the tree should look like:

             1 -> NULL
           /  \
          2 -> 3 -> NULL
         / \    \
        4-> 5 -> 7 -> NULL

     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 == NULL)
    15             return;
    16             
    17         TreeLinkNode *p = root;
    18         TreeLinkNode *q = NULL;
    19         TreeLinkNode *nextNode = NULL;
    20         
    21         while(p)
    22         {
    23             if (p->left)
    24             {
    25                 if (q)
    26                     q->next = p->left;                
    27                 q = p->left;
    28                 if (nextNode == NULL)
    29                     nextNode = q;
    30             }
    31             
    32             if (p->right)
    33             {
    34                 if (q)
    35                     q->next = p->right;
    36                 q = p->right;
    37                 if (nextNode == NULL)
    38                     nextNode = q;
    39             }
    40             
    41             p = p->next;
    42         }
    43         
    44         connect(nextNode);
    45     }
    46 };
  • 相关阅读:
    Pyhont 高阶函数
    Python 函数式编程
    Python 递归函数
    Python 函数的参数定义
    Lniux学习-AWK使用
    Windows10 下 VirtualBox6 中 Centos8 无法安装"增强功能"
    Linux学习-Shell-系统启动过程与执行方式
    接口测试-工具介绍
    Linux学习-Sed 命令
    Linux学习-命令行参数、函数
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787857.html
Copyright © 2011-2022 走看看