I am trying to implement a basic Binary search tree.
I was able to create a Node and I have problems with the AddNode() function. It is supposed to add a new node to the existing tree but it replaces it.
Any ideas what should be done in the AddNode() function ?
class Node
{
public int value { get; set; }
public Node left { get; set; }
public Node right { get; set; }
public Node(int i)
{
this.value = i;
this.left = null;
this.right = null;
}
}
class Tree
{
public Node root { get; set; }
public Tree(Node n)
{
root = n;
}
public void AddNode(int valueToBeInserted)
{
if (this.root == null)
{
this.root = new Node(valueToBeInserted);
// problem here : existing tree is destroyed.
// a new one is created.
// instead it should add a new node to the end of the tree if its null
}
if (valueToBeInserted < this.root.value)
{
this.root = this.root.left;
this.AddNode(valueToBeInserted);
}
if (valueToBeInserted > this.root.value)
{
this.root = this.root.right;
this.AddNode(valueToBeInserted);
}
}
public void printTree()
{
// print recursively the values here.
}
}
class TreeTest
{
public void Test()
{
var tree = new Tree(new Node(100));
tree.AddNode(20);
tree.AddNode(100);
}
}
Thanks.
These lines replace the root:
this.root = this.root.left;
this.root = this.root.right;
You should instead pass a parameter to your recursive function.
You can also remove the this quantifiers - they're only necessary when you have a local variable with the same name or perhaps in some other corner cases.
Adding a helper function is useful / necessary since the root must be catered for separately.
Updated code:
public void AddNode(int valueToBeInserted)
{
if (root == null)
{
root = new Node(valueToBeInserted);
}
else
{
AddNode(valueToBeInserted, root);
}
}
private void AddNode(int valueToBeInserted, Node current)
{
if (valueToBeInserted < current.value)
{
if (current.left == null)
current.left = new Node(valueToBeInserted);
else
AddNode(valueToBeInserted, current.left);
}
if (valueToBeInserted > current.value)
{
if (current.right == null)
current.right = new Node(valueToBeInserted);
else
AddNode(valueToBeInserted, current.right);
}
}
This statement will only be true the first time you run your code.
if (this.root == null)
{
this.root = new Node(valueToBeInserted);
}
Nowhere does the this.root get set to null again...
Normally you would code the add like this:
public void AddNode(int valueToBeInserted)
{
if (this.root == null)
{
this.root = new Node(valueToBeInserted);
}
if (valueToBeInserted < this.root.value)
{
this.root.left = this.AddNode(valueToBeInserted);
this.root = this.root.left;
}
if (valueToBeInserted > this.root.value)
{
this.root.right = this.AddNode(valueToBeInserted);
this.root = this.root.right;
}
}
Related
Im implementing a stack using a linked list. I am having trouble with my pop method where tail.previous is null. I think this is because im trying to assign to the node after the tail which doesnt exist. if this is the case, how can i fix it.
class DynamicStack<T>
{
private class Node
{
public T element { get; private set; }
public Node Next { get; set; }
public Node Previous { get; set; }
public Node(T element, Node prevNode)
{
this.element = element;
Next = null;
Previous = null;
if (prevNode != null)
prevNode.Next = this;
}
}
private Node head, tail;
public int Count { get; private set; }
public DynamicStack()
{
this.head = null;
this.tail = null;
this.Count = 0;
}
public T Pop()
{
if (Count == 0)
return default(T);
Node temp = tail;
tail = tail.Previous;
Count--;
return temp.element;
}
}
I have tried doing the pop method as below but it doesnt follow LIFO so its not correct.
public T Pop()
{
if (Count == 0)
return default(T);
Node temp = head;
head = head.Next;
Count--;
return temp.element;
}
I am trying to do a simple inorder traversal of a BST and the BST builds properly but when I try to print the BST inorder it goes to the first left node and then doesn't go to any other nodes after that and creates an overflow.
Ive tried to do different inorder traversals with getLeft and getRight but it is still doing the same thing
class Program
{
static void Main(string[] args)
{
Tree tree = new Tree();
List<int> rands = new List<int>();
Random random = new Random();
int between = random.Next(20, 30);
for (int i = 0; i < between; i++)
{
rands.Add(random.Next(100));
}
for (int x = 0; x < rands.Count; x++)
{
tree.constructTree(rands[x]);
}
tree.Inorder(tree.returnRoot());
}
class Node
{
private int number;
public Node left;
public Node right;
public Node()
{
}
public Node getLeft()
{
return this.left;
}
public Node getRight()
{
return this.right;
}
public int GetSetNumber
{
get
{
return this.number;
}
set
{
this.number = value;
}
}
public Node GetSetLeft
{
get
{
return this.left;
}
set
{
this.left = value;
}
}
public Node GetSetRight
{
get
{
return this.right;
}
set
{
this.right = value;
}
}
}
class Tree
{
public Node root;
public Node returnRoot()
{
return this.root;
}
public void constructTree(int num)
{
Node t = new Node();
t.GetSetNumber = num;
if (root == null)
{
root = t;
}
else
{
Node cur = root;
Node top;
while (true)
{
top = cur;
if (num < top.GetSetNumber)
{
cur = cur.GetSetLeft;
if (cur == null)
{
top.GetSetLeft = t;
return;
}
}
else
{
cur = cur.GetSetRight;
if (cur == null)
{
top.GetSetRight = t;
return;
}
}
}
}
}
public void Inorder(Node Root)
{
if (root == null)
{
return;
}
Inorder(root.left);
Console.WriteLine(root.GetSetNumber + " ");
Inorder(root.right);
}
}
You are referencing root in Inorder, not Root. root (lower-case r) is the class variable containing the root of the entire tree, not the Node parameter you have passed in. Your code loops infinitely because you are calling Inorder on the same node forever.
If you capitalize your references to root in Inorder (or use a different variable name in the method to avoid confusion, like current) you should be able to make some progress.
public void Inorder(Node Root)
{
if (Root == null)
{
return;
}
Inorder(Root.left);
Console.WriteLine(Root.GetSetNumber + " ");
Inorder(Root.right);
}
I keep getting an unhandled exception
"Object reference not set to an instance of an object"
for the following code, specifically on the line temp.next = node. Can anyone help me figure out why?
The code below is a class for birds where the user inputs a name and the addBird method is suppose to add the name to the end of the linked list.
class BirdsSurve {
private Node first;
public class Node
{
public string Name { get; set; }
public int count { get; set; }
public Node next;
public Node()
{
this.count = 1;
}
public void setNext(Node Next)
{
next = Next;
}
public int addCount()
{
count++;
return count;
}
}
public BirdsSurvey()
{
this.first = null;
}
public void addBird(string bird)
{
Node node = new Node();
node.Name = bird;
if (first == null)
{ first = node; }
else
{
Node temp = first;
while (temp != null)
{
if (temp.Name == bird)
{ temp.addCount(); }
if (temp.next == null)
{
temp = temp.next;
temp.next = node; }
// temp = temp.next;
}
}
}
You set temp to temp.next within the if clause, which checks, if temp.next is null. So, you basically set temp to be null. So, you get the error, because you try to get a next property from a variable, which is null and not an object.
As a side note, maybe rethink the naming of your variables, so that they are not all the same, because that can become confusing quite fast.
This is my implementation for BST (Binary Search Tree). Can Anyone help me to create two methods, one to Connect Leafs and one to return a List of Nodes around the Tree, for example: Connecting Leaf Example In this picture it shows how the leafs should be connected, Nodes that should be stored in List and the way the nodes stored in List need to be in this way where the root is the first element and going to the left passing down to leafs going back to root from the right. In my example it should be 8(root), 3, 1, 4, 7, 13, 14, 10, 8(root).
Thank You!
**class Node
{
private int VL;
private int Niv;
public Node Parent, LC, RC;
public Node()
{
this.Parent = this.LC = this.RC = null;
this.Niv = -1;
}
public Node(int x)
{
this.VL = x;
this.Parent = this.LC = this.RC = null;
this.Niv = -1;
}
public int Vlera
{
get { return this.VL; }
set { this.VL = value; }
}
public int Niveli
{
get { return this.Niv; }
set { this.Niv = value; }
}
}
class BSTree
{
public Node Root;
private int MaxNiv;
public BSTree()
{
this.Root = null;
this.MaxNiv = -1;
}
public void Insert(int x)
{
Node tmp = new Node(x);
if (this.Root == null)
{
tmp.Niveli = 0;
this.Root = tmp;
}
else InsertNode(tmp);
if (tmp.Niveli > this.MaxNiv) MaxNiv = tmp.Niveli;
}
public void ConnectLeafs()
{
//TODO
}
public List<T> ReturnNodesAroundTheTree()
{
//TODO
}
public Node GoTo_Node(Node nd)
{
return GoTo_Node_Rec(this.Root, nd);
}
public Node GoTo_Node(int x)
{
return GoTo_Node_Rec(this.Root, x);
}
private Node GoTo_Node_Rec(Node root, Node nd)
{
if (root.Vlera == nd.Vlera) return root;
if (root.Vlera > nd.Vlera) return GoTo_Node_Rec(root.LC, nd);
else return GoTo_Node_Rec(root.RC, nd);
}
private Node GoTo_Node_Rec(Node root, int x)
{
if (root.Vlera == x) return root;
if (root.Vlera > x) return GoTo_Node_Rec(root.LC, x);
else return GoTo_Node_Rec(root.RC, x);
}
private void InsertNode(Node nd)
{
Node tmp = InsertRecNode(this.Root, nd.Vlera);
if (nd.Vlera >= tmp.Vlera) tmp.RC = nd;
else tmp.LC = nd;
nd.Parent = tmp;
nd.Niveli = nd.Parent.Niveli++;
//if (nd.Niveli > this.MaxNiv) MaxNiv = nd.Niveli;
}
private Node InsertRecNode(Node root, int x)
{
if (x >= root.Vlera)
if (root.RC != null) return InsertRecNode(root.RC, x);
else return root;
else
if (root.LC != null) return InsertRecNode(root.LC, x);
else return root;
}
private bool IsRoot(Node nd)
{
if (nd.Parent == null) return true;
return false;
}
private bool IsLeaf(Node nd)
{
if (nd.LC == null && nd.RC == null) return true;
return false;
}**
Here is the easy way to do this. I created a List of all the node. When you create a new node add node to list. See code below
class BSTree
{
public Node Root;
private int MaxNiv;
private List<Node> nodes = new List<Node>();
public BSTree()
{
this.Root = null;
this.MaxNiv = -1;
}
public void Insert(int x)
{
Node tmp = new Node(x);
nodes.Add(tmp);
if (this.Root == null)
{
tmp.Niveli = 0;
this.Root = tmp;
}
else InsertNode(tmp);
if (tmp.Niveli > this.MaxNiv) MaxNiv = tmp.Niveli;
}
public void ConnectLeafs()
{
//TODO
}
public List<Node> ReturnNodesAroundTheTree()
{
return nodes.Where(x => IsLeaf(x)).ToList();
}
}
I'm trainee and have a problem with that I can't solve this problem alone. So please help me. I found many topics but I could not find a solution.
I just start to learn C# and I'm not sure how to do this. I know that is a simple job but realy I need to understand and solve it. I try to do something but it is only some code. I did my binary tree with some values, have a node class and print method.
Please tell me how to write a code that can read a tree from the Console, because I don't want to have any hardcorde. And then how to find a lowest common ancestor - I see the BFS and DFS algorithms so maybe I can find something, but I'm not sure.
I've read much about this but I can not explain many things. Her
Here is the my code:
class Program
{
static void Main(string[] args)
{
var binatyTree = new BinaryTree<int>(1,
new BinaryTree<int>(2,
new BinaryTree<int>(4),
new BinaryTree<int>(5)),
new BinaryTree<int>(3,
new BinaryTree<int>(6,
new BinaryTree<int>(9),
new BinaryTree<int>(10)),
new BinaryTree<int>(7))
);
Console.WriteLine("Binary Tree:");
binatyTree.Print();
}
}
my binary tree and print method:
public class BinaryTree<T>
{
public T Value { get; set; }
public BinaryTree<T> LeftChildren { get; set; }
public BinaryTree<T> RightChildren { get; set; }
public BinaryTree(T value, BinaryTree<T> leftChildren = null, BinaryTree<T> rightChildren = null)
{
this.Value = value;
this.LeftChildren = leftChildren;
this.RightChildren = rightChildren;
}
public void Print (int indent = 0)
{
Console.Write(new string (' ', 2*indent));
Console.WriteLine(this.Value);
if (this.LeftChildren != null)
{
this.LeftChildren.Print(indent + 1);
}
if (this.RightChildren != null)
{
this.RightChildren.Print(indent + 1);
}
}
my class Node:
class Node
{
private int data;
private Node left;
private Node right;
public Node(int data = 0)
{
this.data = 0;
left = null;
right = null;
}
}
So please I realy need to understand every connections so please if you can explain for me and help.
So here is my Binary tree code.
using System;
namespace MyBinaryTree
{
// Creates a binary tree
// Finds the lowest common ancestor in a binary tree
class МainSolution
{
static void Main(string[] args)
{
// Initialises binary tree view
var btView = new ViewBinaryTree();
btView.BinaryTreeView();
// Initialises new binary tree
BinarySearchTree tree = new BinarySearchTree();
// Reads the desired number of nodes
Console.Write("Enter how many nodes you want: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine();
// Reads the nodes' values
for (int i = 1; i <= number; i++)
{
Console.Write($"Enter name of {i} node: ");
string nodeName = Console.ReadLine().ToUpper();
tree.Insert(nodeName);
}
// Lowest common ancestor - reads the two required values
// Checks the values
// Prints the lowest common ancestor
bool isValid = true;
while (isValid)
{
Console.WriteLine();
Console.Write("Please enter the first node value: ");
string nameOne = Console.ReadLine().ToUpper();
Console.Write("Please enter the second node value: ");
string nameTwo = Console.ReadLine().ToUpper();
if (tree.Find(nameOne) == true && tree.Find(nameTwo) == true)
{
Console.WriteLine();
var result = tree.SearchLCA(tree.root, nameOne, nameTwo);
Console.WriteLine($"Lowest common ancestor: {result} ");
Console.WriteLine();
isValid = false;
}
else
{
Console.WriteLine();
Console.WriteLine("Please enter a valid name!");
}
}
}
}
}
Create a class Node:
// Creates the node structure
class Node
{
public string Data { get; set; }
public Node RightChild { get; set; }
public Node LeftChild { get; set; }
public Node(string data, Node left = null, Node right = null)
{
this.Data = data;
this.LeftChild = left;
this.RightChild = right;
}
}
Here is my logic
// Creates a binary tree.
class BinarySearchTree
{
public Node root; // Creates a root node.
public BinarySearchTree()
{
this.root = null;
}
// Adds a node in the binary tree.
public void Insert(string inputValue)
{
Node newNode = new Node(inputValue); // Creates a new node.
if (root == null) // If the tree is empty, inserts the new node as root
{
root = newNode;
return;
}
//Determins where to place the new node in the binary tree.
Node current = root;
Node parent = null;
while (true)
{
parent = current;
if (inputValue.CompareTo(current.Data) < 0)
{
current = current.LeftChild;
if (current == null)
{
parent.LeftChild = newNode;
return;
}
}
else
{
current = current.RightChild;
if (current == null)
{
parent.RightChild = newNode;
return;
}
}
}
}
// Checks if the node exists in the binary tree
public bool Find(string inputValue)
{
Node current = root;
while (current != null)
{
if (current.Data.Equals(inputValue))
{
return true;
}
else if (current.Data.CompareTo(inputValue) > 0)
{
current = current.LeftChild;
}
else
{
current = current.RightChild;
}
}
return false;
}
// Creates a method to find the lowest common ancestor(LCA).
public object SearchLCA(Node searchTree, string compareValue1, string compareValue2)
{
if (searchTree == null)
{
return null;
}
if (searchTree.Data.CompareTo(compareValue1) > 0 && searchTree.Data.CompareTo(compareValue2) > 0)
{
return SearchLCA(searchTree.LeftChild, compareValue1, compareValue2);
}
if (searchTree.Data.CompareTo(compareValue1) < 0 && searchTree.Data.CompareTo(compareValue2) < 0)
{
return SearchLCA(searchTree.RightChild, compareValue1, compareValue2);
}
return searchTree.Data;
}
}
"Thank you!"