欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-20 20:11:51
...
/*
// 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) {
		queue<Node*> q;
		if (root != NULL) 
			q.push(root);
		while (!q.empty()) 
		{
			int size = q.size();
			Node *node;
			Node *pre_node;
			for (int i = 0; i < size; i++)
			{
				if (i == 0)
				{
					node = q.front();
					q.pop();
					pre_node = node;
				}
				else
				{
					node = q.front();
					q.pop();
					pre_node->next = node;
					pre_node = pre_node->next;
				}
                if(node->left)
                {
                    q.push(node->left);
                }
                if(node->right)
                {
                    q.push(node->right);
                }
			}
			pre_node->next == NULL;
		}
		return root;

	}
};

害,还是要慢慢刷题