xinyu04

导航

LeetCode 117 Populating Next Right Pointers in Each Node II

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.

Solution

按层将下一层的节点按照左右子节点的顺序 \(push\) 进队列,此时的顺序就是 \(next\) 的顺序,所以直接循环即可

点击查看代码
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
private:
    queue<Node*> q;
public:
    Node* connect(Node* root) {
        if(!root) return NULL;
        q.push(root);
        while(!q.empty()){
            int n = q.size();
            Node* prev =NULL;
            Node* tmp;
            while(n--){
                tmp = q.front(); q.pop();
                if(prev) prev->next = tmp;
                prev = tmp;
                if(prev->left)q.push(prev->left);
                if(prev->right)q.push(prev->right);
            }
            tmp->next = NULL;
        }
        return root;
    }
};






posted on 2022-08-03 16:00  Blackzxy  阅读(16)  评论(0编辑  收藏  举报