详细思路

本想递归,能力不足,这道题更适合层序遍历,在第i层遍历已经建好的next节点,为下一层建立next节点,然后进入下一层继续,
 
精确定义
beg为每一次头结点
i为遍历当前节点,需要处理
newBeg新的头结点,在合适和地方赋值,如果为空,最好是第一个i->left
pre i的前一个节点,可以next连接i,并在连接后赋值为当前i
class Solution {
public:
    Node* connect(Node* root) {
        Node*beg=root;
        while(beg){
            Node*newBeg=nullptr;
            for(Node*i=beg;i!=nullptr;i=i->next){
                Node*pre=nullptr;
                if(i->left)connectTwo(pre,i->left,newBeg);
                if(i->right)connectTwo(pre,i->right,newBeg);
            }
            beg=newBeg;
        }
        return root;
    }
    void connectTwo(Node*&pre,Node*cur,Node*newBeg){
        if(pre)pre->next=cur;
        pre=cur;
        if(!newBeg)newBeg=cur;
    }
};

 

踩过的坑
别迷信递归,一些题很明显用层序遍历更好
           Node*newBeg=nullptr;                Node*pre=nullptr;
newBeg和pre都是先当做nullptr,然后交换两节点的时候及时
posted on 2021-08-02 14:57  offer快到碗里来~  阅读(40)  评论(0)    收藏  举报