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));
                
            }
            
        }
    };
    
    
  • 相关阅读:
    [算法] 带权图
    哥德巴赫猜想 ——— 极限算法(你要是能写出比我用时还短的代码算我输)
    详解 位运算
    内存对齐模式 —— 原理讲解
    C语言 文件操作
    指针与数组
    队列的实现
    堆栈的实现
    线性表 详讲及使用
    树莓派
  • 原文地址:https://www.cnblogs.com/dacc123/p/9291712.html
Copyright © 2011-2022 走看看