Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Zad2
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[] t = {4, 2, 3, 7, 1, 5, 6};
- DrzewoBST<int> d0 = CreateTreeFromArray(t);
- Console.WriteLine(d0.Height());
- Console.ReadKey();
- }
- public static DrzewoBST<T> CreateTreeFromArray<T>(T[] array) where T : IComparable<T>
- {
- DrzewoBST<T> tree = new DrzewoBST<T>();
- foreach (T item in array)
- {
- tree.Insert(item);
- }
- return tree;
- }
- }
- class DrzewoBST<T> where T : IComparable<T>
- {
- class Node
- {
- public T value;
- public Node left;
- public Node right;
- public Node(T value)
- {
- this.value = value;
- }
- }
- Node root;
- public DrzewoBST()
- {
- this.root = null;
- }
- // Wstawianie rekurencyjne
- public void Insert(T value)
- {
- Node node = new Node(value);
- if (this.root == null)
- {
- this.root = node;
- }
- else
- {
- Insert(this.root, node);
- }
- }
- private void Insert(Node root, Node node)
- {
- if (root.value.CompareTo(node.value) > 0)
- {
- if (root.left == null)
- {
- root.left = node;
- }
- else
- {
- Insert(root.left, node);
- }
- }
- else
- {
- if (root.right == null)
- {
- root.right = node;
- }
- else
- {
- Insert(root.right, node);
- }
- }
- }
- // Wysokość drzewa
- public int Height()
- {
- return Height(this.root);
- }
- private int Height(Node node)
- {
- int height = 0;
- if (node == null) return 0;
- if (node.left != null)
- {
- height = Math.Max(height, Height(node.left) + 1);
- }
- if (node.right != null)
- {
- height = Math.Max(height, Height(node.right) + 1);
- }
- return height;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement