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

使用BFS

/**
 * 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) {
        if(root == NULL)    return;

        queue<TreeLinkNode *> que;
        que.push(root);
        que.push(NULL);

        TreeLinkNode *prev = NULL;
        while(!que.empty()){
            TreeLinkNode *cur = que.front();
            que.pop();

            if(cur != NULL){
                if(cur->left)
                    que.push(cur->left);
                if(cur->right)
                    que.push(cur->right);

                if(prev)
                    prev->next = cur;

                prev = cur;
            }else{
                if(que.empty()) return;

                prev = NULL;
                que.push(NULL);
            }
        }
    }
};

题目要求使用常量空间

class Solution {
public:
    void connect(TreeLinkNode *root) {
        //记录当前节点的孩子的前一个节点
        TreeLinkNode *prev = NULL;
        //记录当前节点
        TreeLinkNode *cur = root;
        //记录下一层开始的节点
        TreeLinkNode *head = NULL;

        while(cur){
            //遍历cur这一层
            while(cur){
                if(cur->left){
                    if(prev){
                        prev->next = cur->left;
                    }else{
                        head = cur->left;
                    }
                    prev = cur->left;
                }

                if(cur->right){
                    if(prev){
                        prev->next = cur->right;
                    }else{
                        head = cur->right;
                    }
                    prev = cur->right;
                }

                //没有孩子节点,跳过,prev保持不变
                cur = cur->next;
            }
            //调到下一层,一定要更新head的值,不然不会终止
            prev = NULL;
            cur = head;
            head = NULL;
        }
    }
};

results matching ""

    No results matching ""