AC solution, Iterative, very concise cpp!


  • 0
    C
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            while (root) {
                TreeLinkNode* cur = root;
                root = NULL;
                TreeLinkNode* last = new TreeLinkNode(0);
                while (cur) {
                    if (cur->left) {
                        last->next = cur->left;
                        last = last->next;
                        if (!root) root = last; // find the most left node in next level;
                    }
                    if (cur->right) {
                        last->next = cur->right;
                        last = last->next;
                        if (!root) root = last; // find the most left node in next level;
                    }
                    cur = cur->next;
                }
            }
        }
    };

Log in to reply
 

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