leetcode_117 填充每个节点的下一个右侧节点指针 II

1. 题意

在一颗树的同层之间用指针把他们链接起来。

填充每个节点的下一个右侧节点指针 II

2. 题解

2.1 BFS

用一个变量记录下同层最右侧的节点,当遍历到时更新下一层的最右侧节点即可。

class Solution {
public:
    Node* connect(Node* root) {
        Node *righMost = root;

        queue<Node *> q;
        if (root)
            q.push(root);

        while (!q.empty()) {
            Node *cur = q.front();
            q.pop();
            if ( cur -> left) 
                q.push(cur->left);
            if ( cur->right )
                q.push(cur->right);

            if (cur == righMost) {
                righMost = q.back();
            }
            else {
                cur->next = q.front();
            }
        }

        return root;
    }
};
2.2 BFS+空间优化

在将下一层的节点放入队列时,其实就可以将他们链接起来了。从而省去了队列的空间,此时保存下每一层的最开始的节点就可以了。

class Solution {
public:
    void handle(Node *&pre, Node *&nextStart,Node *rt) {
        if (nullptr == rt) return ;

        if (!pre) {
            nextStart = rt;
        }
        else {
            pre->next = rt;
        }
        pre = rt;
    }

    Node* connect(Node* root) {
        Node *righMost = root;

        
        Node *start = root;
        
        Node *nextStart = nullptr;
        Node *pre = nullptr;

        for ( ;start; start = nextStart) {
            nextStart = nullptr;
            pre = nullptr;
            for ( ;start;start = start->next) {
                handle(pre, nextStart, start->left);
                handle(pre, nextStart, start->right);
            }
        }


        return root;
    }
};
2.3 DFS序+层次记录

利用先序遍历的永远是从左到又这一特点,用一个pre[depth]数组来记录当前DFS遍历到的该层的左侧节点。当再次遍历到该层时,链接pre[depth]节点到当前节点,并更新。

class Solution {
public:
    void handle(Node *&pre, Node *&nextStart,Node *rt) {
        if (nullptr == rt) return ;

        if (!pre) {
            nextStart = rt;
        }
        else {
            pre->next = rt;
        }
        pre = rt;
    }
    void dfs(std::vector<Node*> &pre, Node *root, int depth) {
        if (nullptr == root)
            return;
        
        int sz = pre.size();
        if (sz == depth) {
            pre.push_back(root);
        }
        else {
            pre[depth]->next = root;
            pre[depth] = root;
        }
        dfs(pre, root->left, depth + 1);
        dfs(pre, root->right, depth + 1);
    }

    Node* connect(Node* root) {
        
        vector<Node *> pre;
        dfs(pre, root, 0);

        return root;
    }
};

3. Ref

03xf题解

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值