xinyu04

导航

LeetCode 116 Populating Next Right Pointers in Each Node 思维

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

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

我们用两个指针分别遍历每一层的最左端,另一个指针来遍历该层。

点击查看代码
/*
// 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 {
public:
    Node* connect(Node* root) {
        if(!root) return NULL;
        auto head = root;
        for(; root; root = root -> left) 
            for(auto cur = root; cur; cur = cur -> next)           
                if(cur -> left) {                            
                    cur -> left -> next = cur -> right;
                    if(cur -> next) 
                        cur -> right -> next = cur -> next -> left;
                }
                else break;                                         
        return head;
    }
};


posted on 2022-07-22 16:28  Blackzxy  阅读(17)  评论(0编辑  收藏  举报