Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BinaryTree
- {
- public class Node
- {
- public object inf; //информационное поле
- public Node left; //ссылка на левое поддерево
- public Node rigth; //ссылка на правое поддерево
- //конструктор вложенного класса, создает узел дерева
- public Node(object nodeInf)
- {
- inf = nodeInf;
- left = null;
- rigth = null;
- }
- //добавляет узел в дерево так, чтобы дерево оставалось деревом бинарного поиска
- public static void Add(ref Node r, object nodeInf)
- {
- if (r == null)
- {
- r = new Node(nodeInf);
- }
- else
- {
- if (((IComparable)(r.inf)).CompareTo(nodeInf) > 0)
- {
- Add(ref r.left, nodeInf);
- }
- else
- {
- Add(ref r.rigth, nodeInf);
- }
- }
- }
- public static void Preorder(Node r) //прямой обход дерева
- {
- if (r != null)
- {
- Console.Write("{0} ", r.inf);
- Preorder(r.left);
- Preorder(r.rigth);
- }
- }
- public int getNodeHeight()
- {
- int leftHeight = left == null ? 0 : left.getNodeHeight();
- int rightHeight = rigth == null ? 0 : rigth.getNodeHeight();
- Console.WriteLine(1 + Math.Max(leftHeight, rightHeight));
- return 1 + Math.Max(leftHeight, rightHeight);
- }
- }
- Node tree; //ссылка на корень дерева
- //свойство позволяет получить доступ к значению информационного поля корня дерева
- public object Inf
- {
- set
- {
- tree.inf = value;
- }
- get
- {
- return tree.inf;
- }
- }
- public BinaryTree()
- {
- tree = null;
- }
- private BinaryTree(Node r)
- {
- tree = r;
- }
- public void Add(object nodeInf) //добавление узла в дерево
- {
- Node.Add(ref tree, nodeInf);
- }
- public int GetHeight()
- {
- return tree == null ? 0 : tree.getNodeHeight();
- }
- public void Preorder()
- {
- Node.Preorder(tree);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment