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     }
    
    
    
     
  • 相关阅读:
    整理前端面试题1
    前端面试题2
    6.显示锁Lock 和 线程通信Condition
    5.创建执行线程的方式之三 :实现Callable 接口
    4.闭锁 CountDownLatch
    3.ConcurrentHashMap 锁分段机制 Copy-On-Write
    2.原子变量 CAS算法
    1.volatile关键字 内存可见性
    13.MyBatis注解式开发
    12.查询缓存
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3411240.html
Copyright © 2011-2022 走看看