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));
                
            }
            
        }
    };
    
    
  • 相关阅读:
    深度学习中常见问题
    freespace
    跑superpixel的程序
    python处理图片的一些操作
    跑edgebox
    tensorflow安装
    matlab启动
    stixel 理解
    stixel-world跑在kitti数据集
    小议中国人的乡土情结
  • 原文地址:https://www.cnblogs.com/dacc123/p/9291712.html
Copyright © 2011-2022 走看看