美文网首页
Populating Next Right Pointers i

Populating Next Right Pointers i

作者: DaiMorph | 来源:发表于2019-05-04 12:42 被阅读0次

如果当前层所有结点的next 指针已经设置好了,那么据此,下一层所有结点的next指针 也可以依次被设置。

class Solution {
public:
    void connect(TreeLinkNode *root) {
        while(root)
        {
            TreeLinkNode*next=NULL,*pre=NULL;//next指示下一层的开始节点,pre把一层的节点串起来
            for(;root;root=root->next)//遍历root这一层的节点
            {
                if(!next)next=root->left?root->left:root->right;
                if(root->left)
                {
                    if(pre)pre->next=root->left;
                    pre=root->left;
                }
                if(root->right)
                {
                    if(pre)pre->next=root->right;
                    pre=root->right;
                }
            }
            root=next;
        }
    }
};

相关文章

网友评论

      本文标题:Populating Next Right Pointers i

      本文链接:https://www.haomeiwen.com/subject/cbrxoqtx.html