leetcode【BFS】-----117. Populating Next Right Pointers in Each NodeII(填充每个节点的下一个节点)

1、题目描述

2、分析

        这道题和上一道题很像,都是BFS的应用。

3、代码

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() {}

    Node(int _val, Node* _left, Node* _right, Node* _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/
class Solution {
public:
    Node* connect(Node* root) {
        if(root==NULL) return NULL;
        Node* head=root;
        queue<Node*> q;
        q.push(head);
        int size=0;
        while(!q.empty()){
            
            size=q.size();
            for(int i=0;i<size-1;++i){
                Node* cur=q.front();
                q.pop();
                if(q.empty()) cur->next=NULL;
                else cur->next=q.front();
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
            }
             Node* nextcur=q.front();
             q.pop();
            if(nextcur->left) q.push(nextcur->left);
            if(nextcur->right) q.push(nextcur->right);
        }
        return root;
    }
};

4、相关知识点

        二叉树的层序遍历,BFS的应用。

posted @ 2019-07-23 19:58  吾之求索  阅读(82)  评论(0)    收藏  举报