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

1、题目描述

2、分析

        这道题是放在DFS里面的,但是很明显其实用BFS来做会更容易,和树的层序遍历的顺序一样,对每一个节点设置其next指针的位置即可。

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-21 21:00  吾之求索  阅读(105)  评论(0)    收藏  举报