Populating Next Right Pointers in Each Node I & II

来源:互联网 发布:蚂蚁分类信息系统 源码 编辑:程序博客网 时间:2024/05/13 23:58

由于这个题目的I是II的子集(I是II的一种特殊情况),所以II能通过的代码I肯定也可以通过。

咋一看题目没想太多,直接想到用两个队列,一个放当前层的节点,另一个放当前层节点的子节点(下一层),然后循环给每层节点的next赋值。

class Solution {private:    bool checkend(queue <TreeLinkNode*> que){                while(!que.empty()){            if(que.front()->left || que.front()->right)                return true;            que.pop();        }                return false;    }public:    void connect(TreeLinkNode *root) {         queue <TreeLinkNode*> parent;        queue <TreeLinkNode*> child;                if(!root)            return;                parent.push(root);                while(checkend(parent)){                        while(!parent.empty()){                if(parent.front()->left)                    child.push(parent.front()->left);                if(parent.front()->right)                    child.push(parent.front()->right);                parent.pop();            }                        while(!child.empty()){                parent.push(child.front());                child.pop();                                if(!child.empty())                    parent.back()->next=child.front();            }        }            }};

然后看到了题目有一段You may only use constant extra space。。。

呵呵,那就是不能用队列了咯。。。网上参考了[1],发现一个更直接的方法,就是小于等于当前结点层的结点next都已经处理完毕,然后只需递归调用右孩子和左孩子(顺序不能倒过来!暂时没想明白为什么)。

class Solution {public:    void connect(TreeLinkNode *root) {         if (root == NULL) {              return;          }            TreeLinkNode* p = root->next;            while (p != NULL) {              if (p->left != NULL) {                  p = p->left;                  break;              }              if (p->right != NULL) {                  p = p->right;                  break;              }              p = p->next;          }            if (root->right != NULL) {              root->right->next = p;          }            if (root->left != NULL) {              root->left->next = root->right == NULL ? p : root->right;          }            connect(root->right);          connect(root->left);              }};

以上两种方法在II运行时间一样,在I中第二种方法比第一种长一倍时间。


参考:

[1] http://blog.csdn.net/wzy_1988/article/details/17412025

0 0
原创粉丝点击