首页 > 其他 > 详细

【树】117. 填充每个节点的下一个右侧节点指针 II

时间:2020-05-02 14:21:06      阅读:35      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) 
    {
        Node *n = root;
        while (n)
        {
            // the first node of next level
            Node * next = NULL;
            // previous node on the same level
            Node * prev = NULL;
            for (; n; n=n->next)
            {
                if (!next)
                    next = n->left ? n->left:n->right;

                if (n->left)
                {
                    if (prev) prev->next = n->left;
                    prev = n->left;
                }
                if (n->right)
                {
                    if (prev)
                    {
                        prev->next = n->right;
                    }
                    prev = n->right;
                }
            }
            n = next; // turn to next level
        }
        return root;
    }
};

 

【树】117. 填充每个节点的下一个右侧节点指针 II

原文:https://www.cnblogs.com/ocpc/p/12817786.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!