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
    

    Discuss

    /**
     * Definition for binary tree with next pointer.
     * struct TreeLinkNode {
     *  int val;
     *  TreeLinkNode *left, *right, *next;
     *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void connect(TreeLinkNode *root) 
        {
            if(!root)
                return ;
            queue<TreeLinkNode*> qu;
            TreeLinkNode *te;
            int cntb = 0;
            int cnta = 0;
            qu.push(root);
            cntb = 1;
            while(!qu.empty())
            {
                te = qu.front();
                qu.pop();
                cntb--;
                if(cntb == 0)
                {
                    te->next = NULL;
                    if(te->left)
                    {
                        qu.push(te->left);
                        cnta++;
                    }
                     if(te->right)
                    {
                        qu.push(te->right);
                        cnta++;
                    }
                    cntb = cnta;
                    cnta = 0;
                    continue;
                }
                else
                    te->next = qu.front();
                if(te->left)
                {
                    qu.push(te->left);
                    cnta++;
                }
                if(te->right)
                {
                    qu.push(te->right);
                    cnta++;
                }
                
            }
        }
    };

    有了上一次的基础, 一次AC应该没问题
    注意的是:
    queue
    pop()出队
    push(obj);入队
    empty();
    front(); 是队首, 是最先入队的那个.
    也就是说, queue是尾进头出
    back();同理
    还有一个size();
    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    需学习
    CentOS中一些基本的操作记录
    允许IIS下载无后缀文件及“请求的内容似乎是脚本,因而将无法由静态文件处理程序来处理。”的解决方法
    sql server使用的注意点及优化点 自备
    kali 系列学习02
    kali 系列学习01
    运维自动化之13
    运维自动化之12
    运维自动化之11
    运维自动化之10
  • 原文地址:https://www.cnblogs.com/vintion/p/4116979.html
Copyright © 2011-2022 走看看