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

  • 相关阅读:
    洛谷 P2831 [NOIP2016]愤怒的小鸟
    洛谷 P1736 创意吃鱼法
    洛谷 P2347 砝码称重 + bitset简析
    洛谷 P3384 [模板] 树链剖分
    洛谷 P1038 [NOIP2012] 借教室
    洛谷 P3959 [NOIP2017]宝藏 题解
    洛谷 AT2167 Blackout 题解
    洛谷 P1246 编码 题解
    C#中ref关键字的用法总结
    C#中的值传递与引用传递(in、out、ref)
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3779874.html
Copyright © 2011-2022 走看看