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

    题目链接

    Given a binary tree

        struct TreeLinkNode {
          TreeLinkNode *left;
          TreeLinkNode *right;
          TreeLinkNode *next;
        }
    

    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

    Initially, all next pointers are set to NULL.

    Note:

    • You may only use constant extra space.
    • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

    For example,
    Given the following perfect binary tree,

             1
           /  
          2    3
         /   / 
        4  5  6  7
    

    After calling your function, the tree should look like:

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



    Accepted Code:
     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 solve(TreeLinkNode *root) {
    12         // deal with leaf nodes
    13         if (root->left == NULL || root->right == NULL) return;
    14         root->left->next = root->right;
    15         if (root->next != NULL) root->right->next = root->next->left;
    16         else root->right->next = NULL;
    17         // recursive solve left and right child of root
    18         solve(root->left);
    19         solve(root->right);
    20     }
    21     void connect(TreeLinkNode *root) {
    22         if (root == NULL) return ;
    23         root->next = NULL;
    24         solve(root);
    25     } 
    26 };

  • 相关阅读:
    Kotlin系列之序列(Sequences)源码完全解析
    JVM不稳定参数
    akka共享内存
    内存占用过高 kill 调整mysql内存占用
    系统级监控
    linux环境变量
    进程启动,崩溃异常日志++++
    JVM致命错误日志(hs_err_pid.log)分析
    批处理之坑爹的感叹号和变量延迟扩展
    kafka消费端
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3779874.html
Copyright © 2011-2022 走看看