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 };

  • 相关阅读:
    Kafka 再均衡监听器示例
    Spring boot中异步线程池
    【Java&Go并发编程系列】4.等待一组并发任务完成——CountDownLatch VS sync.WaitGroup
    Redis常用命令对应到Redisson对象操作
    js清空缓存,ajax
    phpexcel用法 转、
    composer 使用
    转:git操作
    手机微信内支付
    微信扫码支付
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3779874.html
Copyright © 2011-2022 走看看