Untitled
unknown
plain_text
2 years ago
4.3 kB
4
Indexable
using System;
class Node
{
public int Value;
public Node Left, Right;
public Node(int value)
{
Value = value;
Left = Right = null;
}
}
class BinaryTree
{
private Node root;
public void BuildTree(string input)
{
char[] inputChars = input.ToCharArray();
int index = 0;
root = BuildTree(inputChars, ref index);
}
private Node BuildTree(char[] inputChars, ref int index)
{
if (index >= inputChars.Length || inputChars[index] == '*')
{
index++;
if (index < inputChars.Length && inputChars[index] == '*')
{
// Handle two consecutive '*' characters
index++;
return null;
}
return null;
}
if (char.IsDigit(inputChars[index]))
{
int value = 0;
while (index < inputChars.Length && (char.IsDigit(inputChars[index]) || inputChars[index] == '-'))
{
value = value * 10 + (inputChars[index] - '0');
index++;
}
Node node = new Node(value);
node.Left = BuildTree(inputChars, ref index);
node.Right = BuildTree(inputChars, ref index);
return node;
}
else if (inputChars[index] == 'L' || inputChars[index] == 'P')
{
Node node = new Node(-1); // Zmiana wartości na -1 zamiast 0
index++;
node.Left = BuildTree(inputChars, ref index);
node.Right = BuildTree(inputChars, ref index);
return node;
}
// Handling other characters or unexpected situations
index++;
return null;
}
public void PreorderTraversal()
{
PreorderTraversal(root);
Console.WriteLine();
}
public void InorderTraversal()
{
InorderTraversal(root);
Console.WriteLine();
}
public void PostorderTraversal()
{
PostorderTraversal(root);
Console.WriteLine();
}
public void RemoveTree()
{
RemoveTree(root);
root = null;
}
private void PreorderTraversal(Node node)
{
if (node != null)
{
Console.Write(node.Value + " ");
if (node.Left != null || node.Right != null)
{
PreorderTraversal(node.Left);
PreorderTraversal(node.Right);
}
}
}
private void InorderTraversal(Node node)
{
if (node != null)
{
if (node.Left != null)
{
InorderTraversal(node.Left);
}
Console.Write(node.Value + " ");
if (node.Left != null || node.Right != null)
{
InorderTraversal(node.Right);
}
}
}
private void PostorderTraversal(Node node)
{
if (node != null)
{
if (node.Left != null || node.Right != null)
{
PostorderTraversal(node.Left);
PostorderTraversal(node.Right);
}
Console.Write(node.Value + " ");
}
}
private void RemoveTree(Node node)
{
if (node != null)
{
RemoveTree(node.Left);
RemoveTree(node.Right);
node.Left = null;
node.Right = null;
}
}
}
class Program
{
static void Main()
{
Console.WriteLine("Podaj ciąg znaków (cyfry, 'L', 'P', '*'): ");
string input = Console.ReadLine();
BinaryTree tree = new BinaryTree();
tree.BuildTree(input);
Console.WriteLine("Preorder traversal drzewa:");
tree.PreorderTraversal();
Console.WriteLine("Inorder traversal drzewa:");
tree.InorderTraversal();
Console.WriteLine("Postorder traversal drzewa:");
tree.PostorderTraversal();
tree.RemoveTree();
Console.WriteLine("Drzewo zostało usunięte z pamięci RAM.");
Console.ReadKey();
}
}
Editor is loading...
Leave a Comment