Populating Next Right Pointers in Each Node II

LeetCode #117


Description:

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.

/**
 * 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) {}
 * };
 */

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

Idea:

Iteration: 两个pointer,一个指向下一层的第一个(first),另一个指向下一层的前一个(pre)。

Code:

class Solution {
public:
    void connect(TreeLinkNode *root) {
        while(root!=NULL){
            TreeLinkNode *first=NULL, *pre=NULL;
            while(root!=NULL){
                if(first==NULL){
                    first=root->left!=NULL ? root->left : root->right;
                }
                if(root->left!=NULL){
                    if(pre!=NULL) pre->next=root->left; // 有可能pre还没被设置
                    pre=root->left; //propagate pre指针
                }
                if(root->right!=NULL){ //搞完左subtree搞右subtree
                    if(pre!=NULL) pre->next=root->right;
                    pre=root->right;
                }
                root=root->next;
            }
            root=first;
        }

    }
};

results matching ""

    No results matching ""