二叉树连接右节点(层次遍历)

/* 树中每个节点如果右边有节点 就放置一个指针指向该节点
 * 利用层序遍历 每一层相当于作为一个链表 最左边的节点是头结点 然后穿起来
 * 要用记录层次的遍历法 要么记录一个当前层的长度 要么压入一个空的哨兵
 * */
class Solution {
public:
    Node* connect(Node* root) {
        if(!root)   return NULL;
        queue<Node*> q;
        q.push(root);
        while(!q.empty()){
            int len = q.size();
            for(int i=0;i<len;i++){
                auto p = q.front();q.pop();
                // 除了最后一个节点 都要设置right
                if(i!=len-1)    p->next = q.front();
                if(p->left)     q.push(p->left);
                if(p->right)    q.push(p->right);
            }
        }
        return root;
    }
};

Given a binary tree

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

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.

 

Example:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值