Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BinaryTree
- {
- public BinaryTree()
- {
- this.Count = 0;
- this.Root = null;
- }
- public bool IsEmpty()
- {
- return this.Root == null;
- }
- public void Insert(int value)
- {
- if (IsEmpty())
- {
- this.Root = new Node(value);
- }
- else
- {
- this.Root.Insert(Root, value);
- }
- ++Count;
- }
- public Node FindByValue(int value)
- {
- return this.Root.FindByValue(this.Root, value);
- }
- public bool IsExists(int value)
- {
- return this.Root.IsExists(this.Root, value);
- }
- public override string ToString()
- {
- return this.Root.ToString(Root);
- }
- public Node Root { get; set; }
- public int Count { get; private set; }
- }
- public class Node
- {
- public Node(int rootValue)
- {
- this.Value = rootValue;
- }
- public int Value { get; set; }
- public Node Left { get; set; }
- public Node Right { get; set; }
- public void Insert(Node rootNode, int value)
- {
- if (value < rootNode.Value)
- {
- if (rootNode.Left == null)
- {
- rootNode.Left = new Node(value);
- }
- else
- {
- Insert(this.Left, value);
- }
- }
- else if (value > Value)
- {
- if (rootNode.Right == null)
- {
- rootNode.Right = new Node(value);
- }
- else
- {
- Insert(this.Right, value);
- }
- }
- }
- public bool IsExists(Node rootNode, int value)
- {
- return FindByValue(rootNode, value) != null;
- }
- public bool IsLeaf()
- {
- return (this.Left == null) && (this.Right == null);
- }
- public Node FindByValue(Node rootNode, int value)
- {
- if (rootNode == null) return null;
- if (rootNode.Value == value) return rootNode;
- if (value < rootNode.Value)
- {
- return FindByValue(rootNode.Left, value);
- }
- if (value > rootNode.Value)
- {
- return FindByValue(rootNode.Right, value);
- }
- return null;
- }
- public string ToString(Node rootNode)
- {
- if (rootNode == null) return string.Empty;
- return ToString(rootNode.Left) + " " + rootNode.Value + ToString(rootNode.Right);
- }
- }
Add Comment
Please, Sign In to add comment