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

Populating Next Right Pointers in Each Node II [leetcode] 空间O(1)的基于循环和基于递归的两种方法

时间:2014-09-26 20:11:38      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:leetcode

基于循环的方法:

    void connect(TreeLinkNode *root) {
        if (root == NULL) return;
        TreeLinkNode * start = root;
        TreeLinkNode * end = root;
        TreeLinkNode * levelEnd = root;
        while (start != NULL)
        {
            if (start->left != NULL)
            {
                end->next = start->left;
                end = end->next;
            }
            if (start->right != NULL)
            {
                end->next = start->right;
                end = end->next;
            }
            if (start == levelEnd)
            {
                start = start->next;
                levelEnd->next = NULL;
                levelEnd = end;
            }
            else
            {
                start = start->next;
            }
        }
    }

基于递归的方法

    void connect(TreeLinkNode *curQueue) {
        if (!curQueue) return;
        TreeLinkNode* nextQueue = new TreeLinkNode(-1);//dummy node
        TreeLinkNode* head = nextQueue;
        while (curQueue)
        {
            if (curQueue->left)
            {
                nextQueue->next = curQueue->left;
                nextQueue = nextQueue->next;
            }
            if (curQueue->right)
            {
                nextQueue->next = curQueue->right;
                nextQueue = nextQueue->next;
            }
            curQueue = curQueue->next;
        }
        nextQueue = head;
        head = head->next;
        delete nextQueue;
        connect(head);
    }


Populating Next Right Pointers in Each Node II [leetcode] 空间O(1)的基于循环和基于递归的两种方法

标签:leetcode

原文地址:http://blog.csdn.net/peerlessbloom/article/details/39579977

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