zoukankan      html  css  js  c++  java
  • 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
    Analyse: BFS. Generally, we use queue to do BFS. However, in this problem, we can use the "next pointer" to point to the next node in the same level. When we consider the current level, actually we are dealing with the next level. The structure of the next level likes a linked list
    Runtime: 40ms.
     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         if(!root) return;
    13         
    14         TreeLinkNode pre(-1); //previous node in the level
    15         for(TreeLinkNode* current = root, *move = ⪯ current; current = current->next){
    16             if(current->left){
    17                 move->next = current->left;
    18                 move = move->next;
    19             }
    20             if(current->right){
    21                 move->next = current->right;
    22                 move = move->next;
    23             }
    24             //current = current->next; //children of the current node have been dealt, move to the next node in the level
    25         }
    26         root = pre.next; //assign the first node in the next level to root and begin the new recursion
    27         connect(root);
    28     }
    29 };
  • 相关阅读:
    cppPrimer学习18th
    cppPrimer学习17th
    cppPrimer学习15th
    常用网站记录
    cppPrimer学习16th
    关于nfs内网穿透frp/nps的问题记录
    unp[unix 网络环境编程]学习 vscode环境搭建
    cppPrimer学习14th
    cppPrimer学习14th
    cppPrimer学习13th
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4683662.html
Copyright © 2011-2022 走看看