Deleting a node in BST - linked-list

The code below is are this website
I have some problems with a part of the code here.
I have problem with this line:
root->left = deleteNode(root->left, key);
Why I cannot use simply deleteNode(root->left, key); here?
I want to ask what the function of root->left in this line!
code
/* Given a binary search tree and a key, this function deletes the key
and returns the new root */
struct node* deleteNode(struct node* root, int key)
{
// base case
if (root == NULL) return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if (key < root->key)
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if (key > root->key)
root->right = deleteNode(root->right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's content to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
return root;
}

First of all you need to noticed that the function is not void so you cannot simply use deleteNode(root->left, key).
If I understant correct you want to know what is the returned value and why you put it inside the left (or right) node.
If you didn't get to the node you want to delete root->left = deleteNode(root->left, key); is like using `deleteNode(root->left, key), i.e - just go left .
After you find the node you want to delete there are few options:
1. if you got to node with only one child or no child you update the node value to this one child .
So by type root->left = deleteNode(root->left, key); you update this value .
if there is two sons you you find the inorder successor ( and it is a leaf) and "swap" between there values and than you delete the leaf.
so now root->left = deleteNode(root->left, key); means you update the value to the successor and delete the node.
I hope it was helpfull .

Related

Linked List - Object reference not set to instance of object

I'm writing a method that adds a new Node to the back of a linked list:
public void add(string title, string director, int year, double cost)
{
Node newNode = new Node();
newNode.disc = new BluRayDisc(title, director, year, cost);
Node holder = new Node();
holder = first;
while (holder.next != null) //object reference error
{
holder = holder.next;
}
holder.next = newNode;
}
but am getting a "System.NullReferenceException: 'Object reference not set to an instance of an object.'" error thrown.
The 'first' node is initialized to null so I'm assuming that's where my problem comes from.
This is my first linked list, and this follows the example of an addToBack method I was given exactly. Does anyone have some insight on this problem?
A few issues:
first can be null, which is the case when you start with an empty linked list, and in that case first.next is an invalid reference.
About: Node holder = new Node();. It is not necessary to create a new node here, with new Node(), since in the next statement, you are throwing away that node, by doing holder = first;
Here is the correction:
public void add(string title, string director, int year, double cost)
{
Node newNode = new Node();
newNode.disc = new BluRayDisc(title, director, year, cost);
if (first == null) {
first = newNode;
return;
}
holder = first;
while (holder.next != null) //object reference error
{
holder = holder.next;
}
holder.next = newNode;
}
As you mentioned, the problem is that the variable "first" is initialized to null. It should be set the to the first node of the linked list you are constructing.

Facing a problem while reversing a linked list

I am trying to reverse linked list using java and written below code.
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur=head,prev=null,newHead=null;
while(cur!=null)
{
newHead=cur;
newHead.next=prev;
prev=newHead;
System.out.println(1);
cur=cur.next;
}
return newHead;
}
}
I am not understanding why the loop is executed only once here. Am i doing something wrong?
This happens because you have altered cur.next with the assignment newHead.next=prev;, making it null. Realise that newHead references the same object as cur at that moment.
You should save the original value of cur.next before this change happens:
ListNode cur = head, prev = null, newHead = null, next;
while (cur != null)
{
newHead = cur;
next = cur.next; // <--- save original value of `cur.next`
newHead.next = prev;
prev = newHead;
cur = next; // <--- use that original value here
}

designated Initialization of a Node with a pointer (C++)

When creating a new node in a linked list, is it legal to use designated initializers to initialize the members of the node as mentioned below?
Is there any repercussion in doing so and what would be a better way to achieve the same result?
(lang : C++)
Node *temp = new Node{.data = value, .next = NULL};
struct Node
{
int data;
Node *next;
};
I think you can use function as a constructor.
Node* newFunction(int data) {
Node* newNode = malloc(sizeof(Node));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
And after that, you can use in the main part like that;
Node* newNode = newFunction(5);

Random Binary Tree in Dart

I need to generate random binary trees given only the number of nodes. I want to do it with a linked tree structure with classes. Is it possible? Or is there another way? I couldn't find any resources on this. I suppose a java-like example could work as well.
There's a lot of different ways you might do this. Here's one possible way. It creates the nodes and then connects them by walking through each one and giving it a random parent from the nodes with open spots.
import 'dart:math';
const maxNodes = 10;
void main() {
final rng = Random();
final nodes = List.generate(maxNodes, (index) => Node(index + 1));
final openNodes = [nodes[0]];
nodes.skip(1).forEach((node) {
node.parent = openNodes[rng.nextInt(openNodes.length)];
openNodes.add(node);
if (node.parent.right != null ||
(node.parent.left == null && rng.nextBool())) {
node.parent.left = node;
} else
node.parent.right = node;
if (node.parent.left != null && node.parent.right != null)
openNodes.remove(node.parent);
});
nodes.forEach(print);
}
class Node {
Node(this.id);
final int id;
Node parent;
Node left;
Node right;
#override
String toString() => '$id: (${left?.id ?? '_'}, ${right?.id ?? '_'})';
}
Test it out on DartPad.

Can't recreate just deleted node with UniqueNodeFactory

I just created a node with UniqueNodeFactory and his relationship with UniqueRelationshipFactory. I deleted the the node with the NeoEclipse and then I tried to recreate the same node and I get no exception and the node it's not recreated again. Anyone knows this is happening?
public Node getOrCreateNodeWithUniqueFactory(final Index<Node> nodeIndex, final String indexableKey,final String indexableValue) {
UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory( Global.graphDB.getGraphDbService(), nodeIndex.getName())
{
#Override
protected void initialize(Node created, Map<String, Object> properties) {
created.setProperty(indexableKey, properties.get(indexableKey));
}
};
return factory.getOrCreate( indexableKey, indexableValue );
}
public Relationship getOrCreateRelationshipTypeWithUniqueFactory(Index<Relationship> index, String indexableKey, final String indexableValue,
final RelationshipType type, final Node start, final Node end) {
UniqueFactory<Relationship> factory = new UniqueFactory.UniqueRelationshipFactory(index) {
#Override
protected Relationship create(Map<String, Object> properties) {
Relationship r = start.createRelationshipTo(end, type);
return r;
}
};
return factory.getOrCreate(indexableKey, indexableValue);
}
I can't reproduce your issue. What I get is that there's a new node created the second time around. But it would help with the full source code. And also try with the method "getOrCreateWithOutcome" on UniqueNodeFactory to see whether it was created or not.

Resources