Header Ad

Leetcode Populating Next Right Pointers in Each Node II problem solution

In this Leetcode Populating Next Right Pointers in Each Node II problem solution we have Given a binary tree

struct Node {

  int val;

  Node *left;

  Node *right;

  Node *next;

}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.

Leetcode Populating Next Right Pointers in Each Node II problem solution


Problem solution in Python.

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        ans=[]
        def dfs(node,level):
            if not(node):
                return
            if level==len(ans):
                ans.append([])
            if not(ans[level]):
                ans[level].append(node)
            else:
                ans[level][-1].next=node
                ans[level].append(node)
            dfs(node.left,level+1)
            dfs(node.right,level+1)
        dfs(root,0)
        return root



Problem solution in Java.

public class Solution {   
    public void connect(TreeLinkNode root) {
        connect(root, null);
    }
    
    private void connect(TreeLinkNode root, TreeLinkNode right) {
        if (root == null) return;
        root.next = right;
        TreeLinkNode nextRight = getNextRight(right);
        connect(root.right, nextRight);
        connect(root.left, root.right != null? root.right : nextRight);
    }
    
    private TreeLinkNode getNextRight(TreeLinkNode root) {
        if (root == null) return null;
        TreeLinkNode nextRight = root.left != null? root.left : root.right;
        return nextRight != null? nextRight : getNextRight(root.next);
    }
}


Problem solution in C++.

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


Problem solution in C.

void dfs_fun(struct TreeLinkNode* node,struct TreeLinkNode* next) {
	if(NULL==node) return;
	node->next=next;
	struct TreeLinkNode *beyond_r=NULL;
	while(NULL!=next){
		if(NULL!=next->left){
			beyond_r=next->left;
			break;
		}

		if(NULL!=next->right){
			beyond_r=next->right;
			break;
		}

		next=next->next;
	}

	dfs_fun(node->right,beyond_r);
	dfs_fun(node->left,node->right?node->right:beyond_r);
}

void connect(struct TreeLinkNode *root) {
	dfs_fun(root,NULL);
}


Post a Comment

0 Comments