Populating Next Right Pointers i

2019-05-04  本文已影响0人  DaiMorph

如果当前层所有结点的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;
        }
    }
};
上一篇 下一篇

猜你喜欢

热点阅读