码迷,mamicode.com
首页 > 其他好文 > 详细

Populating Next Right Pointers in Each Node II

时间:2015-05-24 21:57:29      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 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 || (root->left==NULL && root->right==NULL) )
            return;
        
        TreeLinkNode *tmp = root;
        TreeLinkNode *tmp2 = NULL;
        TreeLinkNode *next = NULL;
        
        while(root)
        {
            tmp2 = NULL;
            if(root->left && root->right)
            {
                root->left->next = root->right;
                tmp2 = root->right;
            }
            else if(root->left == NULL)
            {
                tmp2 = root->right;
                tmp2->next = NULL;
            }
            else if(root->right == NULL)
            {
                tmp2 = root->left;
                tmp2->next = NULL;
            }
            
            TreeLinkNode *tmp3 = root->next;
             
            while(tmp3)
            {
                if(tmp3->left || tmp3->right)
                {
                    tmp2->next  = ((tmp3->left != NULL) ? tmp3->left:tmp3->right);
                    next = tmp3;
                    break;
                }
                tmp3 = tmp3->next;
            }
            
            root = tmp3;
        }
        
        if(tmp->left)
            connect(tmp->left);
        if(tmp->right)
            connect(tmp->right);
        
        
    }
};

Populating Next Right Pointers in Each Node II

标签:

原文地址:http://blog.csdn.net/u011412619/article/details/45955433

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!