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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jcolbert30
    New Member
    • May 2010
    • 2

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

    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 WriteTreeLevelT oFile(
    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.Collecti ons.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 WriteTreeLevelT oFile(
    string ("J:\MS_TreeDem o\TreeNode.txt" ),
    TreeNode root,
    int depth);

    }
    }



    Thanks for your help.
    Last edited by jcolbert30; May 13 '10, 04:26 PM. Reason: Changed code in my demo.
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    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.

    Comment

    • jcolbert30
      New Member
      • May 2010
      • 2

      #3
      Originally posted by tlhintoq
      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.
      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_Pr oject\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.WriteLi ne("Exception: " + e.Message);
      }
      finally
      {
      Console.WriteLi ne("Executing finally block.");
      }
      }
      }
      }

      How would you like to see some tags?

      3. This is my Binary Tree generating Code:

      using System;
      using System.Collecti ons.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(Tree Node<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.Collecti ons.IEnumerator System.Collecti ons.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>(ite m);
      ++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(Temp Array, 0, array, arrayIndex, this.NumberOfNo des);
      }

      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(Temp Node.Value);
      }
      foreach (TreeNode<T> TempNode in Traversal(Item. Right))
      {
      Values.Add(Temp Node.Value);
      }
      if (Item.Parent.Le ft == Item)
      {
      Item.Parent.Lef t = null;
      }
      else
      {
      Item.Parent.Rig ht = 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.Equ als(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<Tre eNode<T>> Traversal(TreeN ode<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">ite m 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>(ite m, TempNode);
      ++NumberOfNodes ;
      return;
      }
      else
      {
      TempNode = TempNode.Left;
      }
      }
      else if (ComparedValue > 0)
      {
      if (TempNode.Right == null)
      {
      TempNode.Right = new TreeNode<T>(ite m, 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">Va lue of the node</param>
      public TreeNode(T Value)
      {
      this.Value = Value;
      }

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

      /// <summary>
      /// Constructor
      /// </summary>
      /// <param name="Value">Va lue of the node</param>
      /// <param name="Parent">P arent node</param>
      /// <param name="Left">Lef t node</param>
      /// <param name="Right">Ri ght 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.

      Comment

      • vinaysharma77
        New Member
        • Jun 2010
        • 1

        #4
        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 WriteTreeLevelT oFile(
        string filename,
        TreeNode root,
        int depth);

        Comment

        • Christian Binder
          Recognized Expert New Member
          • Jan 2008
          • 218

          #5
          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.
          Code:
          int myDepth = 0;
          while(parent.Parent != null) {
            myDepth ++;
            parent = parent.Parent;
          }
          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.

          Comment

          Working...