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     }
    
    
    
     
  • 相关阅读:
    Django的路由系统
    Django框架简介
    域名与网站名的区别
    简单的链接样式-CSS
    用Javascript获取样式注意的地方
    null和undefined区别
    addLoadEvent(func)详解
    《Javascrip DOM 编程艺术》学习笔记-Chapter5
    某夜凌晨4点所感所悟——未来前端路
    win7-32bit-virtualbox安装问题及解决方式
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3411240.html
Copyright © 2011-2022 走看看