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

    
    

    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

    Initially, all next pointers are set to NULL.

    Note:

    • You may only use constant extra space.
    • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

    Example:

    Given the following binary tree,

    
    

    After calling your function, the tree should look like:

    这道题目和上一道不同的是,它不是完全二叉树。则不能通过节点数计算是否在哪一层

    c++

    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            
            if(root==NULL) return;
            queue<pair<int,TreeLinkNode*> > q;
            TreeLinkNode* pre = NULL;
            q.push(make_pair(1,root));
            int y = 0;
            while(!q.empty())
            {
                TreeLinkNode* temp = q.front().second;
                int lever = q.front().first;
                q.pop();
                if(lever!=q.front().first||q.empty())
                {
                    if(pre!=NULL)
                        pre->next =temp;
                    temp->next = NULL;
                    pre = NULL;
                }
                else{
                    
                    if(lever!=y) {y=lever;pre = temp; pre->next =NULL;}
                    else { pre->next = temp;pre = temp;pre->next=NULL;
                         } 
                }
             
                if(temp->left!=NULL) q.push(make_pair(lever+1,temp->left));
                if(temp->right!=NULL) q.push(make_pair(lever+1,temp->right));
                
            }
            
        }
    };
    
    
  • 相关阅读:
    LeetCode 4 :Majority Element
    LeetCode 3 :Min Stack
    Oracle操作4
    plsql安装教程
    java Date与String互相转化
    Oracle操作3
    Oracle操作2
    Oracle操作
    Oracle11g修改密码
    Visual Studio2013完全卸载
  • 原文地址:https://www.cnblogs.com/dacc123/p/9291712.html
Copyright © 2011-2022 走看看