c++ 24ms easy-to-understand solution, traversing the node iteratively


  • 2
    public:
        void connect(TreeLinkNode *root) {
            if (root == NULL) return;
            if (root->right == NULL && root->left == NULL) {
                root->next = NULL;
                return;
            }
            root->left->next = root->right;
            root->right->next = NULL;
            TreeLinkNode* dummy = root->left;
            while(dummy->left) {
                TreeLinkNode *tmp = dummy;
                while (tmp) {
                    tmp->left->next = tmp->right;
                    if (tmp->next)
                        tmp->right->next = tmp->next->left;
                    tmp = tmp->next;
                }
                dummy = dummy->left;
            }
        }
    };```

  • 0
    D

    nice and clean!


  • 0

    @duoduo Thanks~~


Log in to reply
 

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