117. 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

解题思路:和前面那题比较像,只是现在的树形是普通的树形。用指针模拟队列。最巧妙的应该是用head指针指向下一层的开头。
/**
 * 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)return ;
        TreeLinkNode* head=root;//The left most node in the lower level
        TreeLinkNode* pre=NULL;//The previous node in the lower level
        TreeLinkNode* cur=NULL;//The current node in the upper level
        while(head){
            cur=head;
            pre=NULL;
            head=NULL;
            while(cur){
                if(cur->left){
                    if(!pre)head=cur->left;
                    else pre->next=cur->left;
                    pre=cur->left;
                    
                }
                if(cur->right){
                    if(!pre)head=cur->right;
                    else pre->next=cur->right;
                    pre=cur->right;
                }
                cur=cur->next;
            }
        }
    }
};

 

posted @ 2017-02-27 22:45  Tsunami_lj  阅读(128)  评论(0编辑  收藏  举报