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

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


题目链接:117. 填充每个节点的下一个右侧节点指针 II

思路:该题如果用的是层次遍历的思想,那么与 116. 填充每个节点的下一个右侧节点指针 题的代码是通用的。

代码如下:

/*
// 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) {
        if(root==NULL)
            return root;

        Node* p =NULL;
        queue<Node*> que;
        que.push(root);
		
		//层次遍历
        while(!que.empty())
        {
            int len=que.size();
            Node* pre=NULL;
            for(int i=0;i<len;i++)
            {
                p=que.front();
                que.pop();
                if(i==0)
                {
                    pre=p;
                    pre->next=NULL;
                }
                else
                {
                    pre->next=p;
                    pre=p;
                    p->next=NULL;
                }
                if(p->left)
                    que.push(p->left);
                if(p->right)
                    que.push(p->right);
            }
        }

        return root;
    }
};

你可能感兴趣的:(leetcode,c++)