首页 > 代码库 > Leetcode:Populating Next Right Pointers in Each Node II

Leetcode:Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

 

For example,
Given the following binary tree,

         1       /        2    3     / \        4   5    7

 

After calling your function, the tree should look like:

         1 -> NULL       /        2 -> 3 -> NULL     / \        4-> 5 -> 7 -> NULL   

分析:此题是Populating Next Right Pointers in Each Node的升级版,去掉了是perfect binary tree的条件,去掉这个条件带来的影响是我们必须查找节点p孩子的next和下一层的head节点,迭代代码如下:
class Solution {public:    void connect(TreeLinkNode *root) {        if(root == NULL) return;                TreeLinkNode *head = root;        while(head){            TreeLinkNode *cur = head;            while(cur){                TreeLinkNode *next = NULL, *p;                //find next node                for(p = cur->next; p && p->left == NULL && p->right == NULL; p = p->next);                if(p == NULL) next = NULL;                else next = p->left?p->left:p->right;                //level link                if(cur->left){                    cur->left->next = cur->right?cur->right:next;                }                if(cur->right)                    cur->right->next = next;                cur = cur->next;            }            //find next head            TreeLinkNode *q;            for(q = head; q && q->left == NULL && q->right == NULL; q = q->next);            if(q == NULL) head = NULL;            else head = q->left?q->left:q->right;        }    }};

上述代码太繁琐,在上面代码的基础上,我们进行简化,实际上在每一层,我们只需维护两个变量,一个next指向下一层的第一个node,一个prev表示同一层的前一个节点。代码如下:

class Solution {public:    void connect(TreeLinkNode *root) {        while (root) {            TreeLinkNode * next = nullptr; // the first node of next level            TreeLinkNode * prev = nullptr; // previous node on the same level            for (; root; root = root->next) {                if (!next) next = root->left ? root->left : root->right;                if (root->left) {                    if (prev) prev->next = root->left;                    prev = root->left;                }                if (root->right) {                    if (prev) prev->next = root->right;                    prev = root->right;                }            }            root = next; // turn to next level        }    }};

 

Leetcode:Populating Next Right Pointers in Each Node II