Populating Next Right Pointers in Each Node II

Q:

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

 

 

A:

使用两个while来搞,这样好像逻辑上清楚一点,内循环只处理当前这一层。

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!root) return;
        root->next = NULL;
        TreeLinkNode* cur_node = root;
        TreeLinkNode* next_level_head = root->left;
        TreeLinkNode* pre = NULL;
        while (cur_node) {
            bool has_next_level = false;
            while (cur_node) {
                if (cur_node->left) {
                    if (pre != NULL) {
                        pre->next = cur_node->left;
                    } else {
                        next_level_head = cur_node->left;
                    }
                    pre = cur_node->left;
                    has_next_level = true;
                }
                
                if (cur_node->right) {
                    if (pre != NULL) {
                        pre->next = cur_node->right;
                    } else {
                        next_level_head = cur_node->right;                        
                    }
                    pre = cur_node->right;
                    has_next_level = true;
                }
                cur_node = cur_node->next;
            }
            if (!has_next_level) break;
            cur_node = next_level_head;
            pre = NULL;
        }
    }
};

 

posted @ 2013-06-25 17:29  dmthinker  阅读(110)  评论(0)    收藏  举报