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));
                
            }
            
        }
    };
    
    
  • 相关阅读:
    JS-Date日期内置对象
    JS-string内置对象
    MyBatis的事务处理
    MyBatis的简单操作
    MyBatis第一个项目示例
    CSS-盒子模型
    百分比布局的使用
    使用TabLayout快速实现一个导航栏
    彻底理解android中的内部存储与外部存储
    Eclipse的LogCat总是自动清空怎么办?
  • 原文地址:https://www.cnblogs.com/dacc123/p/9291712.html
Copyright © 2011-2022 走看看