题解 | #填充每个节点指向最右节点的next指针#

填充每个节点指向最右节点的next指针

https://www.nowcoder.com/practice/fdbd05d647084fcf9be78444e231998b

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
#include <cstddef>
#include <queue>
class Solution {
  public:
    void connect(TreeLinkNode* root) {
        if (root == nullptr)
            return ;
        queue<TreeLinkNode*> qu;
        queue<TreeLinkNode*> jl;
        qu.push(root);
        bool hou = false;
        while (qu.size() > 0 || jl.size() > 0) {
            if (hou == false) {
                TreeLinkNode* t;
                t = qu.front();
                qu.pop();
                if (qu.size() == 0) {
                    t->next = nullptr;
                    hou = true;
                } else
                    t->next = qu.front();
                if (t->left != nullptr) {

                    jl.push(t->left);
                }
                if (t->right != nullptr) {

                    jl.push(t->right);
                }
            } else {
                TreeLinkNode* t;
                t = jl.front();
                jl.pop();
                if (jl.size() == 0) {
                    t->next = nullptr;
                    hou = false;
                } else
                    t->next = jl.front();
                if (t->left != nullptr) {

                    qu.push(t->left);
                }
                if (t->right != nullptr) {

                    qu.push(t->right);
                }
            }

        }
    }
};

全部评论

相关推荐

不亏是提前批,神仙打架,鼠鼠不配了
站队站对牛:现在92都报工艺岗了
投递韶音科技等公司7个岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
今天 14:00
林子大了什么鸟都有啊,我觉得我说的已经很客气了,阴阳谁呢
牛客62656195...:应该不是阴阳吧?你第一次注册的时候boss就说你是牛人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务