zoukankan      html  css  js  c++  java
  • Populating Next Right Pointers in Each Node II

    Description:

    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

    Code:

     1  void connect(TreeLinkNode *root) {
     2         if (!root)
     3             return ;
     4         deque<TreeLinkNode*>a;
     5         deque<TreeLinkNode*>b;
     6         a.push_back(root);
     7         
     8         while (!a.empty())
     9         {
    10             while (!a.empty())
    11             {
    12                 TreeLinkNode* p = a.front();
    13                 a.pop_front();
    14                 if(p->left)
    15                     b.push_back(p->left);
    16                 if(p->right)
    17                     b.push_back(p->right);
    18                
    19                if (a.empty())  
    20                     p->next = NULL; 
    21                else
    22                     p->next = a.front();
    23             }
    24             a = b;
    25             b.clear();
    26         }
    27     }
  • 相关阅读:
    银行业务调度系统
    交通灯管理系统
    Java高新技术
    Java反射机制
    java的集合框架
    正则表达式
    IPD CBB
    TCP的可靠传输(依赖流量控制、拥塞控制、连续ARQ)
    等价类划分
    Pycharm常用配置汇总
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4590649.html
Copyright © 2011-2022 走看看