Populating Next Right Pointers in Each Node II

https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

BFS基本题目,没啥好说的

/**
 * 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) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root == NULL)
        {
            return ;
        }

        list<TreeLinkNode*> queue;
        queue.push_back(root);

        while(!queue.empty())
        {
            int size = queue.size();
            TreeLinkNode* last = NULL;
            for(int i = 0; i<size; i++)
            {
                TreeLinkNode* node = queue.front();
                queue.pop_front();

                if(i == size-1)
                {
                    node->next = NULL;
                }

                if(i != 0)
                {
                    last->next = node;
                }

                last = node;

                if(node->left != NULL)
                {
                    queue.push_back(node->left);
                }

                if(node->right != NULL)
                {
                    queue.push_back(node->right);
                }
            }
        }
    }
};

results matching ""

    No results matching ""