Why reason the member variables LEFT and RIGHT never change when i make the recursive call?
Here's the Source Code:
public class C_Nodo
{
int dato;
C_Nodo left;
C_Nodo right;
public int DATO
{
get { return dato; }
set { dato = value; }
}
public C_Nodo LEFT
{
get { return this.left; }
set { this.left= value; }
}
public C_Nodo RIGHT
{
get { return this.right; }
set { this.right = value; }
}
public C_Nodo(int inf)
{
this.dato = inf;
this.left = null;
this.right = null;
}
}
public class C_Arbol_Bin
{
C_Nodo root;
public C_Arbol_Bin()
{
root = null;
}
Simple insertion in the root or make the recursive call
public void inserta(int dat)
{
if (root == null)
{
root = new C_Nodo(dat);
}
else
{
insert_Order(this.root, dat);
}
}
Here i make the recursive insertion in ordered way depending of the value that contains the father node but RIGH and LEFT never change.
public void insert_Order(C_Nodo tree, int inf)
{
if (tree == null)
{
tree = new C_Nodo(inf);
}
else
{
if (tree.DATO > inf)
{
insert_Order(tree.LEFT, inf);
}
else
{
insert_Order(tree.RIGHT, inf);
}
}
}
}
Declare the function like
public void insert_Order( ref C_Nodo tree, int inf );
Also as this function is an auxiliary function for function inserta then it could be declared like private
What Vlad said...
Basically the reason that the LEFT/RIGHT parts are always null is because you are passing a reference-type object by value, and then call new C_Nodo() on it - this creates a pointer to a new location for your object.
So you can either use Vlad's solution and pass it by reference, or you can change your insert and insert_Order methods to return the Node object and save it in the root node:
public void inserta(int dat)
{
if (root == null)
{
root = new C_Nodo(dat);
}
else
{
this.root = insert_Order(this.root, dat);
}
}
private C_Nodo insert_Order(C_Nodo tree, int inf)
{
if (tree == null)
{
tree = new C_Nodo(inf);
}
else
{
if (tree.DATO > inf)
{
tree.LEFT = insert_Order(tree.LEFT, inf);
}
else
{
tree.RIGHT = insert_Order(tree.RIGHT, inf);
}
}
return tree;
}
Check out this article for more info on references: https://msdn.microsoft.com/en-us/library/s6938f28.aspx
Related
So I have my code implementing Queue in a Linked List version. Everything working, but the display method. I have spent days trying to figure out the right way to display the contents of the nodes in my Queue, without modifying the nodes or queue itself.
This is my code:
public class QueueNode
{
private Object bike;
private QueueNode next;
public QueueNode(Object bike)
{
this.bike = bike;
next = null;
}
public Object Bike //Content
{
get
{
return bike;
}
set
{
bike = value;
}
}
public QueueNode Next //Pointer
{
get
{
return next;
}
set
{
next = value;
}
}
} // end of QueueNode
// This class inherits the interface IQueue, that uses these methods, not relevant here.
public class CircularQueue : IQueue
{
private int capacity = Int32.MaxValue;
private int count = 0;
private QueueNode tail = null; //Node
public int Capacity
{
get
{
return capacity;
}
}
public int Count
{
get
{
return count;
}
}
public bool IsEmpty()
{
return count == 0;
}
public bool IsFull()
{
return count == capacity;
}
public void Enqueue(Object item)
{
// check the pre-condition
if (!IsFull())
{
QueueNode aNode = new QueueNode(item);
if (count == 0) //special case: the queue is empty
{
tail = aNode;
tail.Next = tail;
}
else //general case
{
aNode.Next = tail.Next;
tail.Next = aNode;
tail = aNode;
}
count++;
}
}
public Object Dequeue()
{
// check the pre-condition
if (!IsEmpty())
{
Object data;
if (count == 1) //special case: the queue has only 1 item
{
data = tail.Bike;
tail = null;
}
else //general case
{
data = tail.Next.Bike;
tail.Next = tail.Next.Next;
}
count--;
return data;
}
else
return null;
}
MY PROBLEM: I created this code to display the content of the Nodes (and it display them all), but it ends up modifying the contents, placing the same value in every single node at the end of the task.
/*public void DisplayBikes()
{
if (!IsEmpty())
{
Object data;
for(int i = 0; i <count; i++)
{
data = tail.Next.Bike;
Console.WriteLine(data);
tail.Next = tail.Next.Next;
}
}
else
Console.WriteLine("Sorry. There are no Bikes available");
}*/
Then I went a bit adventurous, and created a temporary Node to display the contents of all the Nodes in my Queue, but ended up being a messed up thing. I got this message:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
tail was null.
So, at this point I have zero idea on how to do this. I know I'm pretty close, but I don't know what I'm missing here, to make this code print the contents of my Nodes....
HELP PLEASE!
public void DisplayBikes()
{
int c = count;
QueueNode temp = tail.Next;
if(!isFull())
{
while(c > 0)
{
Console.WriteLine(temp.Bike);
temp = tail.Next.Next;
c--;
}
}
else
Console.WriteLine("Sorry. There are no Bikes available");
}
SOLVED myself.
public void DisplayBikes()
{
int c = count;
QueueNode temp = tail.Next;
if(!isFull())
{
while(c > 0)
{
Console.WriteLine(temp.Bike);
temp = temp.Next; //Here. I needed to iterate over the same node
c--;
}
}
else
Console.WriteLine("Sorry. There are no Bikes available");
}
That was it. No one dared to help.... So, thank you guys >:(
I'm trying to create an Equals() method which will check if two Binary search trees are identical.
However, when creating 2 BS Trees and calling the Equals method in main, it always returns False.
Please help.
Node Class
class Node<T> where T : IComparable
{
private T data;
public Node<T> Left, Right;
private int balanceFactor;
public Node(T item)
{
data = item;
Left = null;
Right = null;
}
public T Data
{
set { data = value; }
get { return data; }
}
public int BalanceFactor
{
set { balanceFactor = value; }
get { return balanceFactor; }
}
}
BSTree Class
class BSTree<T> : BinTree<T> where T : IComparable
{ //root declared as protected in Parent Class – Binary Tree
public BSTree()
{
root = null;
}
public void InsertItem(T item)
{
insertItem(item, ref root);
}
private void insertItem(T item, ref Node<T> tree)
{
//stopping condition
//simplet tree - what should we do?
if (tree == null)
{
tree = new Node<T>(item);
}
else if(item.CompareTo(tree.Data) < 0)
{
insertItem(item, ref tree.Left);
}
else if (item.CompareTo(tree.Data) > 0)
{
insertItem(item, ref tree.Right);
}
}
public bool Equals(BSTree<T> tree)
{
return Equals(tree,root);
}
private bool Equals(Node<T> root1, Node<T> root2)
{
if (root1 == null && root2 == null)
return true;
if (root1 == null || root2 == null)
{
return false;
}
if (root1.Data.CompareTo(root2.Data) != 0)
return false;
return Equals(root1.Left, root2.Left) && Equals(root1.Right, root2.Right);
}
}
Main
BSTree<int> firstBSTree = new BSTree<int>();
firstBSTree.InsertItem(23);
firstBSTree.InsertItem(12);
firstBSTree.InsertItem(67);
BSTree<int> secondBSTree = new BSTree<int>();
secondBSTree.InsertItem(23);
secondBSTree.InsertItem(12);
secondBSTree.InsertItem(67);
Console.WriteLine(firstBSTree.Equals(secondBSTree));
You are trying to compare BSTree<T> and Node<T>. It calls bool Equals(Object? objA, Object? objB) method of object class. Just pass node of tree.
public bool Equals(BSTree<T> tree)
{
return Equals(tree.root, root);
}
I am learning Data Structure. Today, I wanted to implement Queue using Linked List. As we have FRONT and REAR first index of the entry point of the Queue. If someone asks me to implement a Queue with Linked List, please confirm my below implementation (I am able to achieve the Queue objective without the REAR object.)
Is this implementation valid?
class Queue
{
Node head;
class Node
{
public int Value;
public Node next;
public Node()
{
next = null;
}
}
public void addElement(int val)
{
if (head == null)
{
Node temp = new Node();
temp.Value = val;
head = temp;
return;
}
Node tempNode = head;
while (tempNode.next != null)
{
tempNode = tempNode.next;
}
Node newElement = new Node();
newElement.Value = val;
tempNode.next = newElement;
}
public void Dequeue()
{
if (head != null)
{
if (head.next != null)
{
head = head.next;
return;
}
head = null;
}
}
}
class Program
{
static void Main(string[] args)
{
Queue queue = new Queue();
queue.addElement(10);
queue.addElement(20);
queue.addElement(30);
queue.addElement(40);
queue.Dequeue();
queue.Dequeue();
queue.Dequeue();
queue.Dequeue();
}
}
Well, if we want to have front and rear ends, let's have them:
private Node m_Head;
private Node m_Tail;
You have just one Node head; field and that's why your implementation at least inefficient: you have O(N) time complexity to addElement:
...
while (tempNode.next != null)
{
tempNode = tempNode.next;
}
...
When you can easily have O(1)
I suggest using typical names like Enqueue instead of addElement and have Try methods (often, we don't want exceptions if queue is empty). Finally, let's use generics: MyQueue<T> where T is item's type.
public class MyQueue<T> {
private class Node {
public Node(Node next, T value) {
Next = next;
Value = value;
}
public Node Next { get; internal set; }
public T Value { get; }
}
private Node m_Head;
private Node m_Tail;
public void Enqueue(T item) {
Node node = new Node(null, item);
if (m_Tail == null) {
m_Head = node;
m_Tail = node;
}
else {
m_Tail.Next = node;
m_Tail = node;
}
}
public bool TryPeek(out T item) {
if (m_Head == null) {
item = default(T);
return false;
}
item = m_Head.Value;
return true;
}
public T Peek() {
if (m_Head == null)
throw new InvalidOperationException("Queue is empty.");
return m_Head.Value;
}
public bool TryDequeue(out T item) {
if (m_Head == null) {
item = default(T);
return false;
}
item = m_Head.Value;
m_Head = m_Head.Next;
return true;
}
public T Dequeue() {
if (m_Head == null)
throw new InvalidOperationException("Queue is empty.");
T item = m_Head.Value;
m_Head = m_Head.Next;
return item;
}
}
This is my code for a binary tree program I am doing for an algorithms class. I keep getting a null exception error thrown, but I have no clue what's causing it.
namespace Tree
{
class CallTree
{
static void Main(string[] args)
{
BNode HE = new BNode(0, "House Entrance");
BNode LowerHallway = new BNode(0, "Lower Hallway");
BNode UpperHallway = new BNode(0, "Upper Hallway");
HE.setLeft(LowerHallway);
HE.setRight(UpperHallway);
BNode Lounge = new BNode(0, "Lounge");
BNode Kitchen = new BNode(0, "Kitchen");
LowerHallway.setLeft(Lounge);
LowerHallway.setRight(Kitchen);
BNode Balcony = new BNode(0, "Balcony");
Kitchen.setRight(Balcony);
BNode Study = new BNode(0, "Study");
BNode MasterBedroom = new BNode(0, "Master Bedroom");
UpperHallway.setLeft(Study);
UpperHallway.setRight(MasterBedroom);
BNode GuestBath = new BNode(0, "Guest Bath");
BNode GuestBedroom = new BNode(0, "Guest Bedroom");
Study.setLeft(GuestBath);
Study.setRight(GuestBedroom);
BNode PrivateBath = new BNode(0, "Private Bath");
BNode Closet = new BNode(0, "Closet");
MasterBedroom.setLeft(PrivateBath);
MasterBedroom.setRight(Closet);
HBinaryTree HBinaryTree = new HBinaryTree(HE);
BNode rootNode = HBinaryTree.GetRoot();
I get an exception for 'rootNode' here V
HBinaryTree.preOrder(rootNode);
//HBinaryTree.inOrder(rootNode);
//HBinaryTree.postOrder(rootNode);
Console.ReadKey();
}
}
//definition of node in a binary tree
public class BNode
{
public string room;
public int treasure;
public BNode left, right;//left child and right child
public BNode(int item, string room)
{
treasure = item;
left = null;
right = null;
}
public BNode(int item, string room, BNode leftNode, BNode rightNode)
{
treasure = item;
left = leftNode;
right = rightNode;
}
public void show()
{
Console.Write(treasure);
}
//Is it interial node?
public bool isInner()
{
return left != null || right != null;
}
//Is it a leaf node?
public bool isLeaf()
{
return left == null && right == null;
}
//Does it have a left child?
public bool hasLeft()
{
return left != null;
}
//Does it have a right child?
public bool hasRight()
{
return right != null;
}
//Set its left child to be newLeft
public void setLeft(BNode newLeft)
{
left = newLeft;
}
//Set its right child to be newRight
public void setRight(BNode newRight)
{
right = newRight;
}
//return data value
public int getValue()
{
return treasure;
}
//set data value
public void setValue(int newValue)
{
treasure = newValue;
}
}
//definition of a proper binary tree
class HBinaryTree
{
public BNode root; //root of the tree
public HBinaryTree()
{
root = null;
}
public BNode GetRoot()
{
return root;
}
public HBinaryTree(BNode rootNode) // constructor
{
root = rootNode;
}
// PreOrder traversal
public void preOrder(BNode root)
{
And more exception errors for 'root' in these 4 lines V
root.show();
if (root.isInner())
{
preOrder(root.left);
preOrder(root.right);
}
}
//// InOrder traversal
//public void inOrder(BNode root)
//{
// if (root.isInner())
// {
// inOrder(root.left);
// }
// root.show();
// if (root.isInner())
// {
// inOrder(root.right);
// }
//}
//PostOrder traversal
//public void postOrder(BNode root)
//{
// if (root.isInner())
// {
// postOrder(root.left);
// postOrder(root.right);
// }
// root.show();
//}
}
}
I would like it if someone could help me deduce what is causing the exceptions for 'root' and 'rootNode' to be thrown. It states they are null but I can't understand why it states that.
Your preOrder function recursively calls itself for the left and right nodes off every node in your tree if isInner returns true. isInner returns true if either of its nodes are non-null, but your kitchen has only a right branch, and its left is null. So when that function reaches the kitchen, it sees isInner is true and it calls itself with the left branch off kitchen which is null. You need to check for null for left and right individually.
Let me start off by saying sorry if the title is wrong.
I am being taught Binary Tree Traversal I've been given some of the code, I am really struggling to understand the logic in using the if/else statements and the boolean logic.
I have to traverse the tree using postorder, preorder and inorder methods.
The preorderTraversal method is all ready done and working.
Any suggestions would be appreciated.
The Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BinaryTree
{
class BinaryTree<T>
{
class BinaryTreeNode
{
public BinaryTreeNode Left;
public BinaryTreeNode Right;
public BinaryTreeNode Parent;
public T Data;
public Boolean processed;
public BinaryTreeNode()
{
Left = null;
Right = null;
Parent = null;
processed = false;
}
}
BinaryTreeNode Root;
Comparison<T> CompareFunction;
public BinaryTree(Comparison<T> theCompareFunction)
{
Root = null;
CompareFunction = theCompareFunction;
}
public static int CompareFunction_Int(int left, int right)
{
return left - right;
}
public void preorderTraversal()
{
if (Root != null)
{
BinaryTreeNode currentNode = Root;
Boolean process = true;
int nodesProcessed = 0;
while (nodesProcessed != 11)
{
if (process)
{
Console.Write(currentNode.Data.ToString());
currentNode.processed = true;
nodesProcessed = nodesProcessed +1;
}
process = true;
if (currentNode.Left != null && currentNode.Left.processed == false)
{
currentNode = currentNode.Left;
}
else if (currentNode.Right != null && currentNode.Right.processed ==
false)
{
currentNode = currentNode.Right;
}
else if (currentNode.Parent != null)
{
currentNode = currentNode.Parent;
process = false;
}
}
}
else
{
Console.WriteLine("There is no tree to process");
}
}
public void postorderTraversal()
{
if (Root != null)
{
}
else
{
Console.WriteLine("There is no tree to process");
}
}
public void inorderTraversal()
{
if (Root != null)
{
}
else
{
Console.WriteLine("There is no tree to process");
}
}
public static int CompareFunction_String(string left, string right)
{
return left.CompareTo(right);
}
public void Add(T Value)
{
BinaryTreeNode child = new BinaryTreeNode();
child.Data = Value;
if (Root == null)
{
Root = child;
}
else
{
BinaryTreeNode Iterator = Root;
while (true)
{
int Compare = CompareFunction(Value, Iterator.Data);
if (Compare <= 0)
if (Iterator.Left != null)
{
Iterator = Iterator.Left;
continue;
}
else
{
Iterator.Left = child;
child.Parent = Iterator;
break;
}
if (Compare > 0)
if (Iterator.Right != null)
{
Iterator = Iterator.Right;
continue;
}
else
{
Iterator.Right = child;
child.Parent = Iterator;
break;
}
}
}
}
public bool Find(T Value)
{
BinaryTreeNode Iterator = Root;
while (Iterator != null)
{
int Compare = CompareFunction(Value, Iterator.Data);
if (Compare == 0) return true;
if (Compare < 0)
{
Iterator = Iterator.Left;
continue;
}
Iterator = Iterator.Right;
}
return false;
}
BinaryTreeNode FindMostLeft(BinaryTreeNode start)
{
BinaryTreeNode node = start;
while (true)
{
if (node.Left != null)
{
node = node.Left;
continue;
}
break;
}
return node;
}
public IEnumerator<T> GetEnumerator()
{
return new BinaryTreeEnumerator(this);
}
class BinaryTreeEnumerator : IEnumerator<T>
{
BinaryTreeNode current;
BinaryTree<T> theTree;
public BinaryTreeEnumerator(BinaryTree<T> tree)
{
theTree = tree;
current = null;
}
public bool MoveNext()
{
if (current == null)
current = theTree.FindMostLeft(theTree.Root);
else
{
if (current.Right != null)
current = theTree.FindMostLeft(current.Right);
else
{
T CurrentValue = current.Data;
while (current != null)
{
current = current.Parent;
if (current != null)
{
int Compare = theTree.CompareFunction(current.Data,
CurrentValue);
if (Compare < 0) continue;
}
break;
}
}
}
return (current != null);
}
public T Current
{
get
{
if (current == null)
throw new InvalidOperationException();
return current.Data;
}
}
object System.Collections.IEnumerator.Current
{
get
{
if (current == null)
throw new InvalidOperationException();
return current.Data;
}
}
public void Dispose() { }
public void Reset() { current = null; }
}
}
class TreeTest
{
static BinaryTree<int> Test = new BinaryTree<int>
(BinaryTree<int>.CompareFunction_Int);
static void Main(string[] args)
{
// Build the tree
Test.Add(5);
Test.Add(2);
Test.Add(1);
Test.Add(3);
Test.Add(3); // Duplicates are OK
Test.Add(4);
Test.Add(6);
Test.Add(10);
Test.Add(7);
Test.Add(8);
Test.Add(9);
// Test if we can find values in the tree
for (int Lp = 1; Lp <= 10; Lp++)
Console.WriteLine("Find ({0}) = {1}", Lp, Test.Find(Lp));
// Test if we can find a non-existing value
Console.WriteLine("Find (999) = {0}", Test.Find(999));
// Iterate over all members in the tree -- values are returned in sorted order
foreach (int value in Test)
{
Console.WriteLine("Value: {0}", value);
}
Console.WriteLine("Preorder traversal");
Test.preorderTraversal();
Console.ReadKey();
}
}
}
Use the Recursion, Luke. (Then it's just a matter in what order you visit (and process) the left subtree, right subtree, or the current node itself.)
Here, maybe some nice animations with option to traverse it the way you like, and add and delete so you can have your own example might help: Look at this site
Or maybe CS animation with voice over ... look here.