Sharing a simple C++ iterative solution


  • 0
    Z

    Just saw someone else's idea for Q I, then implement it in Q II
    '''
    class Solution {
    public:

    void connect(TreeLinkNode *root) {
        TreeLinkNode* levelStart = root;
        TreeLinkNode* cur = nullptr;
        while(levelStart) {
            cur = levelStart;
            while(cur) {
                if(cur->left)
                    cur->left->next = cur->right ? cur->right:nextChild(cur->next);
                if(cur->right)
                    cur->right->next = nextChild(cur->next);
                cur = cur->next;
            }
            levelStart = nextChild(levelStart);
        }
    }
    
    TreeLinkNode* nextChild(TreeLinkNode* cur) {
        while(cur) {
            if(cur->left)
                return cur->left;
            if(cur->right)
                return cur->right;
            cur = cur->next;
        }
        return nullptr;
    }
    

    };
    '''


Log in to reply
 

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