Skip to content

Latest commit

 

History

History
57 lines (48 loc) · 1.21 KB

116.md

File metadata and controls

57 lines (48 loc) · 1.21 KB

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

层次遍历

每层从右往左添加结点,记录每个结点的前一个结点。

时间复杂度:O(n)。

空间复杂度:O(n)。

/*
// 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) {
            return root;
        }
        queue<Node*> q;
        q.push(root);
        while (!q.empty()) {
            int size = q.size();
            Node *t = nullptr;
            for (int i = 0; i < size; i++) {
                Node *cur = q.front();
                q.pop();
                cur->next = t;
                t = cur;
                if (cur->right) {
                    q.push(cur->right);
                }
                if (cur->left) {
                    q.push(cur->left);
                }
            }
        }
        return root;
    }
};