【树】117. 填充每个节点的下一个右侧节点指针 II

题目:

【树】117. 填充每个节点的下一个右侧节点指针 II

解答:

/*
// 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) 
    {
        Node *n = root;
        while (n)
        {
            // the first node of next level
            Node * next = NULL;
            // previous node on the same level
            Node * prev = NULL;
            for (; n; n=n->next)
            {
                if (!next)
                    next = n->left ? n->left:n->right;

                if (n->left)
                {
                    if (prev) prev->next = n->left;
                    prev = n->left;
                }
                if (n->right)
                {
                    if (prev)
                    {
                        prev->next = n->right;
                    }
                    prev = n->right;
                }
            }
            n = next; // turn to next level
        }
        return root;
    }
};