117. Populating Next Right Pointers in Each Node II

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了117. Populating Next Right Pointers in Each Node II相关的知识,希望对你有一定的参考价值。

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        TreeLinkNode* head = root;
        while (head) {
            TreeLinkNode* nextHead = NULL, *pre = NULL;
            while (head) {
                TreeLinkNode *left = head->left, *right = head->right;
                if (left) {
                    if (nextHead == NULL)
                        nextHead = left;
                    else
                        pre->next = left;
                    pre = left;
                }
                if (right) {
                    if (nextHead == NULL)
                        nextHead = right;
                    else
                        pre->next = right;
                    pre = right;
                }
                head = head->next;
            }
            head = nextHead;
        }
    }
};

 

以上是关于117. Populating Next Right Pointers in Each Node II的主要内容,如果未能解决你的问题,请参考以下文章

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II

117. Populating Next Right Pointers in Each Node II