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

  • 题目:
    给定一个二叉树

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

初始状态下,所有 next 指针都被设置为 NULL。

示例:

在这里插入图片描述在这里插入图片描述

解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。

  • 解题思路
    方法一:
    利用二叉树的层次遍历,依次将队列节点指向后一个节点,只用在最后一个节点指向空即可。

代码实现:

 Node* connect(Node* root) {
        if(!root)
            return nullptr;
        if(!root->left && !root->right)
            return root;
        deque<Node*> qu;
        qu.push_back(root);
        while(!qu.empty()){
            int size = qu.size();
            for(int i = 0; i < size-1; i++){
                Node* temp = qu.front();
                qu.pop_front();
                temp->next = qu.front();
                if(temp->left)
                    qu.push_back(temp->left);
                if(temp->right)
                    qu.push_back(temp->right);
            }
            Node* temp1 = qu.front();
            temp1->next = nullptr;
            if(temp1->left)
                qu.push_back(temp1->left);
            if(temp1->right)
                qu.push_back(temp1->right);
            qu.pop_front();
        }
        return root;
    }

猜你喜欢

转载自blog.csdn.net/xiao1guaishou/article/details/88225160
今日推荐