Leetcode 116. Populating Next Right Pointers in Each Node

/**
 * 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 == nullptr) return;
        deque d;
        d.push_back(root);

        while(!d.empty()) {
            int n = d.size();
            for (int i = 0; i != n; ++i) {
                TreeLinkNode* r = d.front();
                d.pop_front();
                r->next = (i != n - 1) ? d.front() : nullptr;
                if (r->left != nullptr) d.push_back(r->left);
                if (r->right != nullptr) d.push_back(r->right);
            }
        }
    }
};

你可能感兴趣的:(leetcode,笔记,leetcode)