Simple and short C++ code with O(1) space


  • 0
    L
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if (!root)
                return;
            TreeLinkNode *leftMost, *cur, *rightMost;
            leftMost = root;
            while (leftMost) {
                cur = leftMost;
                leftMost = rightMost = nullptr;
                while (cur) {
                    for (TreeLinkNode* i: {cur->left, cur->right}) {
                        if (!i)
                            continue;
                        if (!leftMost) {
                            leftMost = rightMost = i;
                            continue;
                        }
                        rightMost->next = i;
                        rightMost = i;
                    }
                    cur = cur->next;
                }
            }
        }
    };
    

    Leftmost indicates the the leftmost node in current level.


Log in to reply
 

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