Binary Search Tree in C# Implementation - c#

class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
class BinaryTreeImp
{
Node root;
static int count = 0;
public BinaryTreeImp()
{
root = null;
}
public Node addNode(int data)
{
Node newNode = new Node(data);
if (root == null)
{
root = newNode;
}
count++;
return newNode;
}
public void insertNode(Node root,Node newNode )
{
Node temp;
temp = root;
if (newNode.data < temp.data)
{
if (temp.left == null)
{
temp.left = newNode;
}
else
{
temp = temp.left;
insertNode(temp,newNode);
}
}
else if (newNode.data > temp.data)
{
if (temp.right == null)
{
temp.right = newNode;
}
else
{
temp = temp.right;
insertNode(temp,newNode);
}
}
}
public void displayTree(Node root)
{
Node temp;
temp = root;
if (temp == null)
return;
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
static void Main(string[] args)
{
BinaryTreeImp btObj = new BinaryTreeImp();
Node iniRoot= btObj.addNode(5);
btObj.insertNode(btObj.root,iniRoot);
btObj.insertNode(btObj.root,btObj.addNode(6));
btObj.insertNode(btObj.root,btObj.addNode(10));
btObj.insertNode(btObj.root,btObj.addNode(2));
btObj.insertNode(btObj.root,btObj.addNode(3));
btObj.displayTree(btObj.root);
System.Console.WriteLine("The sum of nodes are " + count);
Console.ReadLine();
}
}
This is the code for implementation.The code works fine but if in the displayTree function , i replace it with
public void displayTree(Node root)
{
Node temp;
temp = root;
while(temp!=null)
{
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
}
an infinite loop is caused. I don't understand what is causing this.Also i would like to know if there is a better way of implementing a BST in C#.

I'm not sure why you need this loop, but answering your question:
while(temp!=null)
{
displayTree(temp.left);
System.Console.Write(temp.data + " ");
displayTree(temp.right);
}
this code checks if temp is not null, but it will never become null, cause inside the loop you act only on the leafs of the temp. That's why you have an infinit loop.

You don't need a while loop nor a temp variable, let recursion do the work for you:
public void displayTree(Node root)
{
if(root == null) return;
displayTree(root.left);
System.Console.Write(root.data + " ");
displayTree(root.right);
}

temp is set to root at the beginning, and after that its value never changes
what about rewriting your function as
public void displayTree(Node root)
{
if (root == null)
return;
displayTree(root.left);
Console.Write(...);
displayTree(root.right);
}

try this
public void displayTree(Node root)
{
Node temp;
temp = root;
if (temp != null)
{
displayTree(temp.left);
Console.WriteLine(temp.data + " ");
displayTree(temp.right);
}
}

I was just thinking that you as well also could use recursion for the add function. It could look something like this
private void Add(BinaryTree node, ref BinaryTree rootNode)
{
if (rootNode == null)
{
rootNode = node;
}
if (node.value > rootNode.value)
{
Add(node, ref rootNode.right);
}
if (node.value < rootNode.value)
{
Add(node, ref rootNode.left);
}
}

See https://msdn.microsoft.com/en-us/library/ms379572%28v=vs.80%29.aspx.
See the example code in the section "Traversing the Nodes of a BST"
Also... don't forget to check out SortedDictionary, etc. They may have the BST that you need all ready to go! https://msdn.microsoft.com/en-us/library/f7fta44c.aspx

Complete Binary Search Tree ... With Code to check whether Tree is balanced or not
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace BinarySearchTree
{
public class Node
{
public Node(int iData)
{
data = iData;
leftNode = null;
rightNode= null;
}
public int data{get; set;}
public Node leftNode{get; set;}
public Node rightNode{get; set;}
};
public class Program
{
public static Node root = null;
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine("Hello, world!");
root = new Node(20);
InsertNode(root, new Node(10));
InsertNode(root, new Node(15));
InsertNode(root, new Node(13));
InsertNode(root, new Node(11));
InsertNode(root, new Node(12));
InsertNode(root, new Node(25));
InsertNode(root, new Node(22));
InsertNode(root, new Node(23));
InsertNode(root, new Node(27));
InsertNode(root, new Node(26));
if(CheckIfTreeIsBalanced(root))
{
Console.WriteLine("Tree is Balanced!");
}
else
{
Console.WriteLine("Tree is Not Balanced!");
}
PrintTree(root);
}
public static void PrintTree(Node root)
{
if(root == null) return;
Node temp = root;
PrintTree(temp.leftNode);
System.Console.Write(temp.data + " ");
PrintTree(temp.rightNode);
}
public static bool CheckIfTreeIsBalanced(Node root)
{
if(root != null)
{
if(root.leftNode != null && root.rightNode!= null)
{
if(root.leftNode.data < root.data && root.rightNode.data > root.data)
{
return CheckIfTreeIsBalanced(root.leftNode)&&CheckIfTreeIsBalanced(root.rightNode);
}
else
{
return false;
}
}
else if(root.leftNode != null)
{
if(root.leftNode.data < root.data)
{
return CheckIfTreeIsBalanced(root.leftNode);
}
else
{
return false;
}
}
else if(root.rightNode != null)
{
if(root.rightNode.data > root.data)
{
return CheckIfTreeIsBalanced(root.rightNode);
}
else
{
return false;
}
}
}
return true;
}
public static void InsertNode(Node root, Node newNode )
{
Node temp;
temp = root;
if (newNode.data < temp.data)
{
if (temp.leftNode == null)
{
temp.leftNode = newNode;
}
else
{
temp = temp.leftNode;
InsertNode(temp,newNode);
}
}
else if (newNode.data > temp.data)
{
if (temp.rightNode == null)
{
temp.rightNode = newNode;
}
else
{
temp = temp.rightNode;
InsertNode(temp,newNode);
}
}
}
}
}
Output :
Hello, world!
Tree is Balanced!
10 11 12 13 15 20 22 23 25 26 27

Related

InsertInOrder Function for a Linkedlist

I'm trying to create a function InsertInOrder() that inserts an item in the correct place without disturbing the order.
Ex:
LinkedList before [3,5,6] after inserting 4 ---> [3,4,5,6].
I have created the function but some reason it's not working as expected.
I'm testing the code on a Windows form application by entering ISBNs,
What went wrong:
First I inserted 23, then I inserted 10, expecting to be placed before 23 but here's what happened (image below):
What went wrong
Please find the code below:
LinkListGen Class
class LinkListGen<T> where T : IComparable
{
private LinkGen<T> list;
public LinkListGen()
{
list = null;
}
public void AddItem(T item)
{
list = new LinkGen<T>(item, list); //create a new link on the front of the list
}
public void AppendItem(T item)
{
LinkGen<T> temp = list;
if (temp == null)
{
list = new LinkGen<T>(item);
}
else
{
while (temp.Next != null)
{
temp = temp.Next;
}
temp.Next = new LinkGen<T>(item);
}
}
public string DisplayList()
{
string buffer = "";
LinkGen<T> temp = list; //temp starts beginning of list
while (temp != null) //not at end of list
{
buffer = buffer + temp.Data.ToString() + ",";
temp = temp.Next; //move along a link
}
return buffer;
}
public void RemoveItem(T item)
{
LinkGen<T> temp = list;
LinkListGen<T> newList = new LinkListGen<T>();
while (temp != null)
{
if (item.CompareTo(temp.Data) != 0)
{
newList.AppendItem(temp.Data);
}
temp = temp.Next;
}
list = newList.list;
}
public void InsertInOrder (T item)
{
LinkGen<T> temp = list;
LinkListGen<T> newList = new LinkListGen<T>();
if (list == null)
{
AppendItem(item);
}
else
{
while (temp != null)
{
if(list.Data.CompareTo(item) < 0)
{
newList.AppendItem(list.Data);
temp = temp.Next;
}
else if(list.Data.CompareTo(item) > 0)
{
newList.AppendItem(item);
newList.AppendItem(list.Data);
temp = temp.Next;
}
newList.AppendItem(list.Data);
temp = temp.Next;
}
}
}
}
Windows Form App code
public partial class Form1 : Form
{
LinkListGen<Book> ISBNList = new LinkListGen<Book>();
public Form1()
{
InitializeComponent();
}
private void AddButton_Click(object sender, EventArgs e)
{
double insertedISBN = Convert.ToDouble(ISBNTextBox.Text);
Book newBook = new Book(insertedISBN);
ISBNList.InsertInOrder(newBook);
DisplayLabel.Text = ISBNList.DisplayList();
}
private void RemoveButton_Click(object sender, EventArgs e)
{
double insertedISBN = Convert.ToDouble(ISBNTextBox.Text);
Book removeBook = new Book(insertedISBN);
ISBNList.RemoveItem(removeBook);
DisplayLabel.Text = ISBNList.DisplayList();
}
}
Your problem, that you call AppendItem at InsertInOrder, which adds element to the end of the list, instead pure pointer manipulation.
At the same time, you shouldn't recreate list at InsertInOrder to avoid memory/time overhead.
Try next code, not tested:
public void InsertInOrder(T item)
{
var node = new LinkGen<T>(item);
if (list == null)
{
list = node;
return;
}
var current = list;
while (current != null)
{
if (current.Data.CompareTo(item) < 0)
{
// current is last element
if (current.Next == null)
{
current.Next = node;
break;
}
// current.Next.Data is equal or greater than new value
// so set new node.Next to current.Next and current.Next to new node
if (current.Next.Data.CompareTo(item) >= 0)
{
node.Next = current.Next;
current.Next = node;
break;
}
}
current = current.Next;
}
}

Printing Tree and skipping certain values

here i have the following code and input that prints a tree structure. My question is how can i make it so that the nodes and leafs that have the value "Unavailable" are skipped from being printed.
namespace Tree{public class TreeNode<T>
{
private T value;
private bool hasParent;
private List<TreeNode<T>> children;
public TreeNode(T value)
{
if (value == null)
{
throw new ArgumentNullException("Cannot insert null value");
}
this.value = value;
this.children = new List<TreeNode<T>>();
}
public T Value
{
get
{
return this.value;
}
set
{
this.value = value;
}
}
public int ChildrenCount
{
get
{
return this.children.Count;
}
}
public void AddChild(TreeNode<T> child)
{
if (child == null)
{
throw new ArgumentNullException("Cannot insert null value");
}
if (child.hasParent)
{
throw new ArgumentException("The node already has a parent");
}
child.hasParent = true;
this.children.Add(child);
}
public TreeNode<T> GetChild(int index)
{
return this.children[index];
}
}
public class Tree<T>
{
private TreeNode<T> root;
public Tree(T value)
{
if (value == null)
{
throw new ArgumentNullException("Cannot insert null value");
}
this.root = new TreeNode<T>(value);
}
public Tree(T value, params Tree<T>[] children) : this(value)
{
foreach (Tree<T> child in children)
{
this.root.AddChild(child.root);
}
}
public TreeNode<T> Root
{
get
{
return this.root;
}
}
private void PrintDFS(TreeNode<T> root, string spaces)
{
if (this.root == null)
{
return;
}
Console.WriteLine(spaces + root.Value);
TreeNode<T> child = null;
for (int i = 0; i < root.ChildrenCount; i++)
{
child = root.GetChild(i);
PrintDFS(child, spaces + " ");
}
}
public void TraverseDFS()
{
this.PrintDFS(this.root, string.Empty);
}
}
public static class TreeExample
{
static void Main()
{
Tree<string> tree =
new Tree<string>("John",
new Tree<string>("Jasmine",
new Tree<string>("Jay"),
new Tree<string>("Unavailable")),
new Tree<string>("Unavailable",
new Tree<string>("Jack"),
new Tree<string>("Jeremy")),
new Tree<string>("Johanna")
);
tree.TraverseDFS();
}
}}
right now it prints :(John, (Jasmine, (Jay), (Unavailable)), (Unavailable, (Jack, (Jeremy))), (Johanna))
I need it to print :(John, (Jasmine, (Jay)), (Johanna))
So basically skip every leaf with the value "Unavailable" and every node with the value "Unavailable" and all children from that node
Thanks !
This should work:
private void PrintDFS(TreeNode<T> root, string spaces)
{
if (this.root == null
|| "Unavailable" == root.Value.ToString())
{
return;
}
...
The accepted answer is a literally correct answer to the question, but it bakes in logic about what to do with the tree into the tree itself. A tree is a kind of collection or data structure, and you don't often see a List or Dictionary that is able to print itself. Instead the collection provides the right methods to get or change its contents so that you can do what you want.
In your case, you could do something like the following:
public enum TreeVisitorResult {
SkipNode,
Continue
}
// the following two methods inside Tree<T>:
public void VisitNodes(Func<TreeNode<T>, int, TreeVisitorResult> visitor) {
VisitNodes(0, this.root, visitor);
}
private void VisitNodes(int depth, TreeNode<T> node,
Func<TreeNode<T>, int, TreeVisitorResult> visitor) {
if (node == null) {
return;
}
var shouldSkip = visitor(node, depth);
if (shouldSkip == TreeVisitorResult.SkipNode) {
return;
}
TreeNode<T> child = null;
for (int i = 0; i < node.ChildrenCount; i++) {
child = node.GetChild(i);
VisitNodes(depth + 1, child, visitor);
}
}
If you had this method, you could write the Print method outside of the Tree classes, as:
tree.VisitNodes((treeNode, depth) => { // <- this lambda will be called for every node
if (treeNode.Value == "Unavailable") { // <- no need to ToString or cast here, since
// we know that T is string here
return TreeVisitorResult.SkipNode;
} else {
var spaces = new string(' ', depth * 3);
Console.WriteLine(spaces + treeNode.Value);
}
});

How to recursively populate a TreeView with JSON data

I have a winforms treeview, I can read data automatically, (a node that is equal to key, and a node inside that is equal to value), but when reading object type, the values inside it are not going to be child of object node (key of object), (maybe I couldnt explain well, here is a screenshot and my methods.)
layer0 needs to be inside textures and scale needs to be inside display
My Json:
{
"parent": "builtin/generated",
"textures": {
"layer0": "mm:items/iron_dust"
},
"display": {
"scale": [ 1.7, 1.7, 1.7 ]
}
}
My method to auto detect(not all mine actually)
private void Form1_Load(object sender, EventArgs e)
{
StreamReader reader = new StreamReader(path);
string json = reader.ReadToEnd();
reader.Close();
JObject obj = JObject.Parse(json);
getAllProperties(obj);
}
void getAllProperties(JToken children)
{
TreeNode mainNode = treeView1.Nodes[0];
mainNode.Text = Path.GetFileNameWithoutExtension(path);
foreach (JToken child in children.Children())
{
var property = child as JProperty;
if (property != null)
{
if (property.Value.Type == JTokenType.String)
{
TreeNode keyNode = mainNode.Nodes.Add(property.Name);
keyNode.Nodes.Add(property.Value.ToString());
}
if (property.Value.Type == JTokenType.Array)
{
JArray array = (JArray)property.Value;
TreeNode node = mainNode.Nodes.Add(property.Name);
for (int i = 0; i < array.Count; i++)
{
node.Nodes.Add(array[i].ToString());
}
}
if (property.Value.Type == JTokenType.Object)
{
TreeNode topNode = mainNode.Nodes.Add(property.Name.ToString());
foreach (var item in property)
{
if (item.Type == JTokenType.String)
{
if (property.Value.Type == JTokenType.String)
{
TreeNode keyNode = topNode.Nodes.Add(property.Name);
keyNode.Nodes.Add(property.Value.ToString());
}
if (property.Value.Type == JTokenType.Array)
{
JArray array = (JArray)property.Value;
TreeNode node = topNode.Nodes.Add(property.Name);
for (int i = 0; i < array.Count; i++)
{
node.Nodes.Add(array[i].ToString());
}
}
}
}
}
// Console.WriteLine(property.Name + ":" + property.Value);//print all of the values
}
getAllProperties(child);
}
}
}
I tried to get parent, but it didnt have name and value properties :S.
Any help?
(Sorry for language mistakes)
The problem is that, as you recursively descend the JToken hierarchy, you also need to recursively descend the TreeNode hierarchy you are creating, adding child nodes to the parent node just created, rather than the root node, along the lines of Recursion, parsing xml file with attributes into treeview c#.
Thus if you do:
private void Form1_Load(object sender, EventArgs e)
{
using (var reader = new StreamReader(path))
using (var jsonReader = new JsonTextReader(reader))
{
var root = JToken.Load(jsonReader);
DisplayTreeView(root, Path.GetFileNameWithoutExtension(path));
}
}
private void DisplayTreeView(JToken root, string rootName)
{
treeView1.BeginUpdate();
try
{
treeView1.Nodes.Clear();
var tNode = treeView1.Nodes[treeView1.Nodes.Add(new TreeNode(rootName))];
tNode.Tag = root;
AddNode(root, tNode);
treeView1.ExpandAll();
}
finally
{
treeView1.EndUpdate();
}
}
private void AddNode(JToken token, TreeNode inTreeNode)
{
if (token == null)
return;
if (token is JValue)
{
var childNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(token.ToString()))];
childNode.Tag = token;
}
else if (token is JObject)
{
var obj = (JObject)token;
foreach (var property in obj.Properties())
{
var childNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(property.Name))];
childNode.Tag = property;
AddNode(property.Value, childNode);
}
}
else if (token is JArray)
{
var array = (JArray)token;
for (int i = 0; i < array.Count; i++)
{
var childNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(i.ToString()))];
childNode.Tag = array[i];
AddNode(array[i], childNode);
}
}
else
{
Debug.WriteLine(string.Format("{0} not implemented", token.Type)); // JConstructor, JRaw
}
}
You will get the following tree view structure:
Here is my crack at it. The output is identical to Notepad++'s JSTool plug-in:
The code is structured as a TreeView extension:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TestDLApp.Utilities.Extensions
{
public static class ObjectToTreeView
{
private sealed class IndexContainer
{
private int _n;
public int Inc() => _n++;
}
private static void FillTreeView(TreeNode node, JToken tok, Stack<IndexContainer> s)
{
if (tok.Type == JTokenType.Object)
{
TreeNode n = node;
if(tok.Parent != null)
{
if(tok.Parent.Type == JTokenType.Property)
{
n = node.Nodes.Add($"{((JProperty)tok.Parent).Name} <{tok.Type.ToString()}>");
}
else
{
n = node.Nodes.Add($"[{s.Peek().Inc()}] <{tok.Type.ToString()}>");
}
}
s.Push(new IndexContainer());
foreach (var p in tok.Children<JProperty>())
{
FillTreeView(n, p.Value, s);
}
s.Pop();
}
else if (tok.Type == JTokenType.Array)
{
TreeNode n = node;
if(tok.Parent != null)
{
if (tok.Parent.Type == JTokenType.Property)
{
n = node.Nodes.Add($"{((JProperty)tok.Parent).Name} <{tok.Type.ToString()}>");
}
else
{
n = node.Nodes.Add($"[{s.Peek().Inc()}] <{tok.Type.ToString()}>");
}
}
s.Push(new IndexContainer());
foreach (var p in tok)
{
FillTreeView(n, p, s);
}
s.Pop();
}
else
{
var name = string.Empty;
var value = JsonConvert.SerializeObject(((JValue)tok).Value);
if (tok.Parent.Type == JTokenType.Property)
{
name = $"{((JProperty)tok.Parent).Name} : {value}";
}
else
{
name = $"[{s.Peek().Inc()}] : {value}";
}
node.Nodes.Add(name);
}
}
public static void SetObjectAsJson<T>(this TreeView tv, T obj)
{
tv.BeginUpdate();
try
{
tv.Nodes.Clear();
var s = new Stack<IndexContainer>();
s.Push(new IndexContainer());
FillTreeView(tv.Nodes.Add("ROOT"), JsonConvert.DeserializeObject<JToken>(JsonConvert.SerializeObject(obj)), s);
s.Pop();
}
finally
{
tv.EndUpdate();
}
}
}
}
You can call it as so:
treeView1.SetObjectAsJson(new MyNeatObject());

reverse a linked list in a recursive function c#

I'm having problems trying to write a reverse recursive method for a LinkedList class I created in C#.
The LinkedList has 2 pointers in it one for the head and the other for the tail:
public class Node
{
public object data;
public Node next;
public Node(object Data)
{
this.data = Data;
}
}
public class LinkedList
{
Node head;
Node tail;
public void Add(Node n)
{
if (head == null)
{
head = n;
tail = head;
}
else
{
tail.next = n;
tail = tail.next;
}
}
Now, the recursive reverse function goes like this:
public void reverse_recursive()
{
Node temp_head = head;
if (temp_head == tail)
{
return;
}
while (temp_head != null)
{
if (temp_head.next == tail)
{
tail.next = temp_head;
tail = temp_head;
reverse_recursive();
}
temp_head = temp_head.next;
}
}
I'm having 2 troubles with it: first, a logic problem, I know that head doesn't point to the first node after the reverse. The second problem is that i probably do something wrong with the null pointer so the program crashes.
I also give you the main program:
class Program
{
static void Main(string[] args)
{
LinkedList L = new LinkedList();
L.Add(new Node("first"));
L.Add(new Node("second"));
L.Add(new Node("third"));
L.Add(new Node("forth"));
L.PrintNodes();
L.reverse_recursive();
L.PrintNodes();
Console.ReadLine();
}
}
Thank you for helping!!
public void Reverse()
{
this.Reverse(this.head);
}
private void Reverse(Node node)
{
if (node != null && node.next != null)
{
// Create temporary references to the nodes,
// because we will be overwriting the lists references.
Node next = node.next;
Node afterNext = node.next.next;
Node currentHead = this.head;
// Set the head to whatever node is next from the current node.
this.head = next;
// Reset the next node for the new head to be the previous head.
this.head.next = currentHead;
// Set the current nodes next node to be the previous next nodes next node :)
node.next = afterNext;
// Keep on trucking.
this.Reverse(node);
}
else
{
this.tail = node;
}
}
public void reverse()
{
reverse_recursive(tail);
Node tmp = tail;
tail = head;
head = tmp;
}
public void reverse_recursive(Node endNode)
{
Node temp_head = head;
if (temp_head == endNode)
{
return;
}
while (temp_head != null)
{
if (temp_head.next == endNode)
{
break;
}
temp_head = temp_head.next;
}
endNode.next = temp_head;
temp_head.next = null;
reverse_recursive(temp_head);
}
See also this
Another option over here.
class Program{
static void Main(string[] args)
{
LinkedList L = new LinkedList();
L.Add(new Node("first"));
L.Add(new Node("second"));
L.Add(new Node("third"));
L.Add(new Node("forth"));
L.PrintNodes();
L.reverse_recursive();
Console.WriteLine("---------------------");
L.PrintNodes();
Console.ReadLine();
}
}
public class Node
{
public object data;
public Node next;
public Node(object Data)
{
this.data = Data;
}
}
public class LinkedList
{
Node head;
Node tail;
public void Add(Node n)
{
if (head == null)
{
head = n;
tail = head;
}
else
{
tail.next = n;
tail = tail.next;
}
}
public void PrintNodes()
{
Node temp = head;
while (temp != null)
{
Console.WriteLine(temp.data);
temp = temp.next;
}
}
private LinkedList p_reverse_recursive(Node first)
{
LinkedList ret;
if (first.next == null)
{
Node aux = createNode(first.data);
ret = new LinkedList();
ret.Add(aux);
return ret;
}
else
{
ret = p_reverse_recursive(first.next);
ret.Add(createNode(first.data));
return ret;
}
}
private Node createNode(Object data)
{
Node node = new Node(data);
return node;
}
public void reverse_recursive()
{
if (head != null)
{
LinkedList aux = p_reverse_recursive(head);
head = aux.head;
tail = aux.tail;
}
}
}
Hope it helps
A second variant
private void p_reverse_recursive2(Node node)
{
if (node != null)
{
Node aux = node.next;
node.next = null;
p_reverse_recursive2(aux);
if (aux != null)
aux.next = node;
}
}
public void reverse_recursive()
{
if (head != null)
{
Node aux = head;
head = tail;
tail = aux;
p_reverse_recursive2(tail);
}
}
Variation on a theme...
public Node Reverse(Node head)
{
if(head == null)
{
return null;
}
Node reversedHead = null;
ReverseHelper(head, out reversedHead);
return reversedHead;
}
public Node ReverseHelper(Node n, out Node reversedHead)
{
if(n.Next == null)
{
reversedHead = n;
return n;
}
var reversedTail = ReverseHelper(n.Next, out reversedHead);
reversedTail.Next = n;
n.Next = null;
return n;
}
}
I was just playing with similar brain teaser with the only difference that LinkedList class only has a definition for head and all the rest of the nodes are linked there. So here is my quick and dirty recursive solution:
public Node ReverseRecursive(Node root)
{
Node temp = root;
if (root.next == null)
return root;
else
root = ReverseRecursive(root.next);
temp.next = null;
Node tail = root.next;
if (tail == null)
root.next = temp;
else
while (tail != null)
{
if (tail.next == null)
{
tail.next = temp;
break;
}
else
tail = tail.next;
}
return root;
}

the program not print output anyone can help

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Node
{
public int Data;
public Node Left;
public Node Right;
public void DisplayNode()
{
Console.Write(Data + " ");
}
}
public class BinarySearchTree
{
public Node root;
public BinarySearchTree()
{
root = null;
}
public void Insert(int i)
{
Node newNode = new Node();
newNode.Data = i;
if (root == null)
root = newNode;
else
{
Node current = root;
Node parent;
while (true)
{
parent = current;
if (i < current.Data)
{
current = current.Left;
if (current == null)
{
parent.Left = newNode;
break;
}
else
{
current = current.Right;
if (current == null)
{
parent.Right = newNode;
break;
}
}
}
}
}
}
public void InOrder(Node theRoot)
{
if (!(theRoot == null))
{
InOrder(theRoot.Left);
theRoot.DisplayNode();
InOrder(theRoot.Right);
}
}
static void Main()
{
BinarySearchTree nums = new BinarySearchTree();
nums.Insert(23);
nums.Insert(45);
nums.Insert(16);
nums.Insert(37);
nums.Insert(3);
nums.Insert(99);
nums.Insert(22);
Console.WriteLine("Inorder traversal: ");
nums.InOrder(nums.root);
}
}
}
You've got an infinite loop in your Insert function; you're handling the case where i < current.data but if i >= current.data then it gets stuck in the while(true). I think you need to move the current = current.right code up a nesting level, i.e.
while (true)
{
parent = current;
if (i < current.Data)
{
current = current.Left;
if (current == null)
{
parent.Left = newNode;
break;
}
}
else
{
current = current.Right;
if (current == null)
{
parent.Right = newNode;
break;
}
}
}
Note the else is now if (i < current.Data) ... else not if (current == null) ... else.
But really you need to learn to use the debugger to diagnose this sort of thing yourself.
Maybe it's
Console.Write(Data.ToString() + " ");

Categories