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     }
    
    
    
     
  • 相关阅读:
    javaScript 与JQuery 计算器练习
    git在java项目中配置.gitignore不生效的解决办法
    mysql8主从复制配置
    ES6的Promise实例
    常用正则表达式
    Redis在Windows环境下后台启动
    Redis数据操作命令 二
    Redis数据操作命令
    List集合学习笔记
    MyBatis学习链接
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3411240.html
Copyright © 2011-2022 走看看