DEV Community

Nic
Nic

Posted on • Originally published at coderscat.com on

LeetCode: Populating Next Right Pointers in Each Node

2020_07_15_populating-next-right-pointers-in-each-node.org_20200715_144225.png

Iteractive algorithm with queue

This is a simple version of level-order traverse.

class Solution {
public:
    Node* connect(Node* root) {
        queue<Node*> Q;
        Node* cur;
        if(root) Q.push(root);
        while(!Q.empty()) {
            int sz = Q.size();
            Node* pre = NULL;
            for(int i=0; i<sz; i++) {
                cur = Q.front(); Q.pop();
                if(cur->left) Q.push(cur->left);
                if(cur->right) Q.push(cur->right);
                if(pre) pre->next = cur;
                pre = cur;
            }
        }
        return root;
    }
};

Enter fullscreen mode Exit fullscreen mode

The post LeetCode: Populating Next Right Pointers in Each Node appeared first on Coder's Cat.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay