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

    思路:
    对于root,如果存在左右节点则,左节点的next是右节点。如果只存在之一的话,那么那么的next节点是root的next中最左边的节点。注意,因为子节点要用到父节点的next信息,所以先遍历右节点后遍历左节点。
    代码:
     
     1     void connect(TreeLinkNode *root) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         if(root){
     5             if(root->left){
     6                 if(root->right){
     7                     root->left->next = root->right;
     8                 }
     9                 else{
    10                     TreeLinkNode *tmp = root->next;
    11                     while(tmp && !root->left->next){
    12                         if(tmp->left)
    13                             root->left->next = tmp->left;
    14                         else
    15                             root->left->next = tmp->right;
    16                         tmp = tmp->next;
    17                     }
    18                 }
    19             }
    20             if(root->right){
    21                 TreeLinkNode *tmp = root->next;
    22                 while(tmp && !root->right->next){
    23                     if(tmp->left)
    24                         root->right->next = tmp->left;
    25                     else
    26                         root->right->next = tmp->right;
    27                     tmp = tmp->next;
    28                 }
    29             }
    30             connect(root->right);
    31             connect(root->left);
    32         }
    33     }
    
    
    
     
  • 相关阅读:
    初见QT---信号和槽(二)
    初见QT---信号和槽
    Python的那些事---数据分析(一)---NumPy基础
    初见QT---创建QPushButton按钮
    初见QT---QT creator常见快捷键使用
    PHP 反射 Reflection
    python 代码求阶乘
    Python中的计时器对象
    python websocket 再线聊天室的 Demo
    Tornado创建一个web服务
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3411240.html
Copyright © 2011-2022 走看看