Concise C++ solution


  • 0
    M
    class Solution {
    private:
        TreeLinkNode *getNext(TreeLinkNode *node) {
            while (node) {
                if (node->left) {
                    return node->left;
                }
                if (node->right) {
                    return node->right;
                }
                node = node->next;
            }
            return nullptr;
        }
    
    public:
        void connect(TreeLinkNode *root) {
            if (!root) {
                return;
            }
            if (root->left) {
                root->left->next = root->right ?: getNext(root->next);
            }
            if (root->right) {
                root->right->next = getNext(root->next);
            }
            connect(root->right);
            connect(root->left);
        }
    };

  • 0

    This is recursive so it violates the constraint of constant (i.e., O(1)) space.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.