LeetCode---Populating Next Right Pointers in Each Node

题目大意:

给出一个二叉树,使得二叉树中每个节点都有一个指针指向其右边的节点。如果节点不存在右边的节点则指针为空。

算法思想:

1.判断根节点是否为空,不空则将更节点和其层号放入队列。

2.当队列不空时,取队头元素cp的并将其移出队列,再取队列一个元素temp.

3.判断temp所记录的节点是否为空且该节点的层号是否和cp的层号相同,如果相同cp的右边节点为temp,否则cp的右边节点为空。

4.判断cp的儿子节点是否为空,不空则入队列。

2.当队列为空时,二叉树转换完毕。

hint:整体算法思想与二叉树的层序遍历思想相似。

代码如下:

/**
 * 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) {
      queue<pair<TreeLinkNode*,int>> Queue;
      pair<TreeLinkNode*,int> cp,temp;
      
      if(root==NULL) return;
      Queue.push(make_pair(root,1));
      
      while(!Queue.empty()){
         cp=Queue.front();
            Queue.pop();
         temp=Queue.front();
         if(temp.first!=NULL&&temp.second==cp.second){
             cp.first->next=temp.first;
         }
         else
            cp.first->next=NULL;
         if(cp.first->left!=NULL)
            Queue.push(make_pair(cp.first->left,cp.second+1));
         if(cp.first->right!=NULL)
            Queue.push(make_pair(cp.first->right,cp.second+1));
            
      }
     
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值