473,507 Members | 6,295 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Write to a file all of the values of a Binary Tree Nodes at the specified depth from.

2 New Member
1. Implement the following C# method to write to a file all the values of the binary tree nodes at the specified depth from the root. Root has depth 0. Start from the leftmost node. An iterative solution is preferred over a recursive one.

class TreeNode
{
public int Value { get; set; }
public TreeNode LeftChild { get; set; }
public TreeNode RightChild { get; set; }
public TreeNode Parent { get; set; }
};

static void WriteTreeLevelToFile(
string filename,
TreeNode root,
int depth);

2. When I enter this code into Visual Studio I get an error at, "Static Void".

3. I need to write the results out to a file.

This is my try at the solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MS_TreeDemo
{
class TreeNode
{
public int Value { get; set; }
public TreeNode LeftChild { get; set; }
public TreeNode RightChild { get; set; }
public TreeNode Parent { get; set; }
};

static void WriteTreeLevelToFile(
string ("J:\MS_TreeDemo\TreeNode.txt"),
TreeNode root,
int depth);

}
}



Thanks for your help.
May 13 '10 #1
4 3242
tlhintoq
3,525 Recognized Expert Specialist
You have explanation but no question. What are you asking?

Also please edit your post to put in code tags as mentioned when you created the post.
May 13 '10 #2
jcolbert30
2 New Member
@tlhintoq
Ok, let me restate my question:

1. How do I write the results of a Binary Tree in C# to a tetx file. I found that part but I have not found how to link the C# code to my main code to get output to a text file.

When you say put tags in my code can you give an example of what you mean, thanks.

2. Here is my output code to a text file:

By The Way, I am using Visual Studio 2008:

//Write a text file
using System;
using System.IO;
using System.Text;

namespace readwriteapp
{
class Class1
{
[STAThread]
static void Main(string[] args)
{

Int64 x;

try
{
//Open the File
StreamWriter sw = new StreamWriter(@"J:\VS_Consol_Project\Test1.txt", true, Encoding.ASCII);

//Writeout the numbers 1 to 10 on the same line.
for (x = 0; x < 10; x++)
{
sw.WriteLine(x);
}

//close the file
sw.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}

How would you like to see some tags?

3. This is my Binary Tree generating Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Binary tree
/// </summary>
/// <typeparam name="T">The type held by the nodes</typeparam>
public class BinaryTree<T> : ICollection<T>, IEnumerable<T> where T : IComparable<T>
{
#region Constructor

/// <summary>
/// Constructor
/// </summary>
public BinaryTree()
{
NumberOfNodes = 0;
}

public BinaryTree(TreeNode<T> Root)
{
this.Root = Root;
NumberOfNodes = 0;
}

#endregion

#region Properties
/// <summary>
/// The root value
/// </summary>
public TreeNode<T> Root { get; set; }

/// <summary>
/// The number of nodes in the tree
/// </summary>
protected int NumberOfNodes { get; set; }

/// <summary>
/// Is the tree empty
/// </summary>
public bool IsEmpty { get { return Root == null; } }

/// <summary>
/// Gets the minimum value of the tree
/// </summary>
public T MinValue
{
get
{
if (IsEmpty)
throw new Exception("The tree is empty");
TreeNode<T> TempNode = Root;
while (TempNode.Left != null)
TempNode = TempNode.Left;
return TempNode.Value;
}
}

/// <summary>
/// Gets the maximum value of the tree
/// </summary>
public T MaxValue
{
get
{
if (IsEmpty)
throw new Exception("The tree is empty");
TreeNode<T> TempNode = Root;
while (TempNode.Right != null)
TempNode = TempNode.Right;
return TempNode.Value;
}
}

#endregion

#region IEnumerable<T> Members

public IEnumerator<T> GetEnumerator()
{
foreach (TreeNode<T> TempNode in Traversal(Root))
{
yield return TempNode.Value;
}
}

#endregion

#region IEnumerable Members

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
foreach (TreeNode<T> TempNode in Traversal(Root))
{
yield return TempNode.Value;
}
}

#endregion

#region ICollection<T> Members

public void Add(T item)
{
if (Root == null)
{
Root = new TreeNode<T>(item);
++NumberOfNodes;
}
else
{
Insert(item);
}
}

public void Clear()
{
Root = null;
}

public bool Contains(T item)
{
if (IsEmpty)
return false;

TreeNode<T> TempNode = Root;
while (TempNode != null)
{
int ComparedValue = TempNode.Value.CompareTo(item);
if (ComparedValue == 0)
return true;
else if (ComparedValue < 0)
TempNode = TempNode.Left;
else
TempNode = TempNode.Right;
}
return false;
}

public void CopyTo(T[] array, int arrayIndex)
{
T[] TempArray = new T[NumberOfNodes];
int Counter = 0;
foreach (T Value in this)
{
TempArray[Counter] = Value;
++Counter;
}
Array.Copy(TempArray, 0, array, arrayIndex, this.NumberOfNodes);
}

public int Count
{
get { return NumberOfNodes; }
}

public bool IsReadOnly
{
get { return false; }
}

public bool Remove(T item)
{
TreeNode<T> Item = Find(item);
if (Item == null)
return false;
List<T> Values = new List<T>();
foreach (TreeNode<T> TempNode in Traversal(Item.Left))
{
Values.Add(TempNode.Value);
}
foreach (TreeNode<T> TempNode in Traversal(Item.Right))
{
Values.Add(TempNode.Value);
}
if (Item.Parent.Left == Item)
{
Item.Parent.Left = null;
}
else
{
Item.Parent.Right = null;
}
Item.Parent = null;
foreach (T Value in Values)
{
this.Add(Value);
}
return true;
}

#endregion

#region Private Functions

/// <summary>
/// Finds a specific object
/// </summary>
/// <param name="item">The item to find</param>
/// <returns>The node if it is found</returns>
protected TreeNode<T> Find(T item)
{
foreach (TreeNode<T> Item in Traversal(Root))
if (Item.Value.Equals(item))
return Item;
return null;
}

/// <summary>
/// Traverses the list
/// </summary>
/// <param name="Node">The node to start the search from</param>
/// <returns>The individual items from the tree</returns>
protected IEnumerable<TreeNode<T>> Traversal(TreeNode<T> Node)
{
if (Node.Left != null)
{
foreach (TreeNode<T> LeftNode in Traversal(Node.Left))
yield return LeftNode;
}
yield return Node;
if (Node.Right != null)
{
foreach (TreeNode<T> RightNode in Traversal(Node.Right))
yield return RightNode;
}
}

/// <summary>
/// Inserts a value
/// </summary>
/// <param name="item">item to insert</param>
protected void Insert(T item)
{
TreeNode<T> TempNode = Root;
bool Found = false;
while (!Found)
{
int ComparedValue = TempNode.Value.CompareTo(item);
if (ComparedValue < 0)
{
if (TempNode.Left == null)
{
TempNode.Left = new TreeNode<T>(item, TempNode);
++NumberOfNodes;
return;
}
else
{
TempNode = TempNode.Left;
}
}
else if (ComparedValue > 0)
{
if (TempNode.Right == null)
{
TempNode.Right = new TreeNode<T>(item, TempNode);
++NumberOfNodes;
return;
}
else
{
TempNode = TempNode.Right;
}
}
else
{
TempNode = TempNode.Right;
}
}
}

#endregion
}

/// <summary>
/// Node class for the Binary tree
/// </summary>
/// <typeparam name="T">The value type</typeparam>
public class TreeNode<T>
{
#region Constructors

/// <summary>
/// Constructor
/// </summary>
public TreeNode()
{
}

/// <summary>
/// Constructor
/// </summary>
/// <param name="Value">Value of the node</param>
public TreeNode(T Value)
{
this.Value = Value;
}

/// <summary>
/// Constructor
/// </summary>
/// <param name="Value">Value of the node</param>
/// <param name="Parent">Parent node</param>
public TreeNode(T Value, TreeNode<T> Parent)
{
this.Value = Value;
this.Parent = Parent;
}

/// <summary>
/// Constructor
/// </summary>
/// <param name="Value">Value of the node</param>
/// <param name="Parent">Parent node</param>
/// <param name="Left">Left node</param>
/// <param name="Right">Right node</param>
public TreeNode(T Value, TreeNode<T> Parent, TreeNode<T> Left, TreeNode<T> Right)
{
this.Value = Value;
this.Right = Right;
this.Left = Left;
this.Parent = Parent;
}

#endregion

#region Properties

/// <summary>
/// Value of the node
/// </summary>
public T Value { get; set; }

/// <summary>
/// Parent node
/// </summary>
public TreeNode<T> Parent { get; set; }

/// <summary>
/// Left node
/// </summary>
public TreeNode<T> Left { get; set; }

/// <summary>
/// Right node
/// </summary>
public TreeNode<T> Right { get; set; }

/// <summary>
/// Is this the root
/// </summary>
public bool IsRoot { get { return Parent == null; } }

/// <summary>
/// Is this a leaf
/// </summary>
public bool IsLeaf { get { return Left == null && Right == null; } }

internal bool Visited { get; set; }

#endregion

#region Public Overridden Functions

public override string ToString()
{
return Value.ToString();
}

#endregion
}

Again, how should I enter tags?

Thanks for your help, this is my first time asking for help.
May 13 '10 #3
vinaysharma77
1 New Member
Did anyone got an answe to the original question.. Question is:
HOW to implement the following C# method to write to a file all the values of the binary tree nodes at the specified depth from the root. Root has depth 0. Start from the leftmost node. An iterative solution is preferred over a recursive one.

class TreeNode
{
public int Value { get; set; }
public TreeNode LeftChild { get; set; }
public TreeNode RightChild { get; set; }
public TreeNode Parent { get; set; }
};

static void WriteTreeLevelToFile(
string filename,
TreeNode root,
int depth);
Jun 6 '10 #4
Christian Binder
218 Recognized Expert New Member
You could use your Traversal(Root)-method. This returns all nodes in a flattened way, beginning with the leftest node as far as I've understood it.

Out of this (all) nodes, you take the nodes with a depth equal to your wanted specific depth.

You can calculate the depth of each node by determining the count of parents e.g.
Expand|Select|Wrap|Line Numbers
  1. int myDepth = 0;
  2. while(parent.Parent != null) {
  3.   myDepth ++;
  4.   parent = parent.Parent;
  5. }
  6.  
I think, this would be the easiest way to achieve your requirements. But it can be very slow if there are many nodes in your tree and there re sure a lot of faster way to get the nodes you want.
Jun 7 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

8
3119
by: Jimmy | last post by:
Hi everyone, I am working with a binary tree, and I am having a bit of trouble visuallizing what needs to happen when I am trying to delete a node that has two children. (no child node and one...
4
806
by: Jerry Khoo | last post by:
Thanks for the answer, and by the way, i would like to know that in C++, how u create a tree using a recursive envronment. It seems that most people used struct to create a node than, using...
7
3612
by: pembed2003 | last post by:
Hi, I have a question about how to walk a binary tree. Suppose that I have this binary tree: 8 / \ 5 16 / \ / \ 3 7 9 22 / \ / \ / \
0
5203
by: Reed | last post by:
Can someone stear me in the right direction to convert a binary tree from a Linked List to a Dynamic Array... Dynamic arrays aren't something im strong with. //********bintree.h******** #ifndef...
5
9553
by: pembed2003 | last post by:
Hi, I have a question about how to walk a binary tree. Suppose that I have this binary tree: 8 / \ 5 16 / \ / \ 3 7 9 22 / \ / \ / \
7
2188
by: abhrajit | last post by:
I'm looking for a C/C++/Java library to create a balanced binary tree data structure given a set of leaf nodes as input. A leaf node should never become an interior node. So if I wish to create...
15
5067
by: Foodbank | last post by:
Hi all, I'm trying to do a binary search and collect some stats from a text file in order to compare the processing times of this program (binary searching) versus an old program using linked...
4
4042
by: Anthony Liu | last post by:
There are many ways to represent a binary tree on an ascii screen. 1 / \ 2 3 / \ / \ 4 5 6 7 or
4
3976
by: APEJMAN | last post by:
would you please help me with this question? I know that a binary tree can be recovered from its pre-order traversal. That is, a tree built from the pre-order traversal should always be the same as...
3
2444
by: FARAECHILIBRU | last post by:
i'm building a binary tree the problem is when i'm reading from e text file .First i'm sending to tree builder function a empty node and e new node the function return me firt node of a tree, but...
0
7105
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7371
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7023
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5617
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5037
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3188
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3178
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1534
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
410
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.