Drzewko
Jungle girlunknown
csharp
2 years ago
2.5 kB
7
Indexable
using System;
using System.Collections.Generic;
namespace DrzewoBinarne
{
public class BinaryTree<T>
{
public BinaryTreeNode<T> Root { get; set; }
public int Count { get; set; }
}
public class TreeNode<T>
{
public T Data { get; set; }
public TreeNode<T> Parent { get; set; }
public List<TreeNode<T>> Children { get; set; }
public int GetHeight()
{
int height = 1;
TreeNode<T> current = this;
while (current.Parent != null)
{
height++;
current = current.Parent;
}
return height;
}
}
public class BinaryTreeNode<T> : TreeNode<T>
{
public BinaryTreeNode() => Children = new List<TreeNode<T>>(){null, null, null};
public BinaryTreeNode<T> Left { get { return (BinaryTreeNode<T>)Children[0]; }
set { Children[0] = value; } }
public BinaryTreeNode<T> Right
{
get { return (BinaryTreeNode<T>)Children[1]; }
set { Children[1] = value; }
}
private void TraversePreOrder(BinaryTreeNode<T> node, List<BinaryTreeNode<T>> result)
{
if (node != null)
{
result.Add(node);
}
TraversePreOrder(node.Left, result);
TraversePreOrder(node.Right, result);
}
}
class Program
{
static void Main(string[] args)
{
BinaryTree<int> binaryTree = new BinaryTree<int>();
binaryTree.Root = new BinaryTreeNode<int>() { Data = 100 };
binaryTree.Root.Left = new BinaryTreeNode<int>() { Data = 50, Parent = binaryTree.Root };
binaryTree.Root.Right = new BinaryTreeNode<int>() { Data = 150, Parent = binaryTree.Root };
binaryTree.Root.Left.Left = new BinaryTreeNode<int>() { Data = 30, Parent = binaryTree.Root.Left };
PrintBinaryTree(binaryTree.Root, "");
}
static void PrintBinaryTree(BinaryTreeNode<int> node, string indent)
{
Console.WriteLine(indent + "└─ " + node.Data);
if (node.Left != null)
{
PrintBinaryTree(node.Left, indent + " ├─ ");
}
if (node.Right != null)
{
PrintBinaryTree(node.Right, indent + " └─ ");
}
}
}
}
Editor is loading...
Leave a Comment