1
Technology, Science & Alt Science / Construct a binary tree from a text file
« on: September 26, 2012, 09:00:50 PM »
I have a text file, and each line represents data in a node. I have to construct a binary tree of it. Also, I have to do it in C#.
The format of the text file is, I think, a preorder traversal or whatever.
Each node will always have two children or no children, but the tree must be able to be any size and still be created using the same program.
So far I've managed to mostly just fuck up. I had something that I think was close, but that was several hours ago, and now I can't remember what I had done.
What I do still have is this:
I'm lost and can't keep my thoughts straight any more, so I figured I'd ask here.
The format of the text file is, I think, a preorder traversal or whatever.
Quote
Root
Root.left
Root.left.left
Root.left.right
Root.right
Root.right.left
Root.right.right
Each node will always have two children or no children, but the tree must be able to be any size and still be created using the same program.
So far I've managed to mostly just fuck up. I had something that I think was close, but that was several hours ago, and now I can't remember what I had done.
What I do still have is this:
Code: [Select]
Node root;
public void ReadFile() //Puts every line of the file into an array.
{
String[] allLines = File.ReadLines("nodeFile.txt").ToArray();
root = WriteTree(allLines, 0);
}
public Node WriteTree(String[] fileContents, int arrayItem)
{
Node node = new Node();
if (fileContents.Length - 1 >= arrayItem)
{
node.Text = fileContents[arrayItem]; //Adds current string to current node.
//Console.WriteLine(fileContents[arrayItem] + " added");
// Need stuff here that adds node.Left and node.Right
// I'm more or less entirely sure this method needs to be recursive
}
return node;
}
I'm lost and can't keep my thoughts straight any more, so I figured I'd ask here.