Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. class BinaryTree
  2. {
  3.  
  4. public Node Root { get; set; }
  5.  
  6. public class Node
  7. {
  8. public int Data { get; set; }
  9. public Node Left { get; set; }
  10. public Node Right { get; set; }
  11.  
  12. public Node(int data)
  13. {
  14. Data = data;
  15. Left = null;
  16. Right = null;
  17. }
  18. }
  19.  
  20. public void Insert(int data)
  21. {
  22. InsertRecursive(data, Root);
  23. }
  24.  
  25. private void InsertRecursive(int data, Node node)
  26. {
  27. Node newNode = new Node(data);
  28.  
  29. // base case
  30. // for non root, if you were lead to a null node, t
  31. // this should be the correct case
  32. if (node == null)
  33. node = newNode;
  34.  
  35. else
  36. {
  37. // if new value > node => go right
  38. if (data > node.Data)
  39. InsertRecursive(data, node.Right);
  40. // if new value < node => go left
  41. else if (data < node.Data)
  42. InsertRecursive(data, node.Left);
  43.  
  44. }
  45. }
  46. static void Main(string[] args)
  47. {
  48. BinaryTree tree2 = new BinaryTree();
  49. tree2.Insert(4);
  50. tree2.Insert(2);
  51. tree2.Insert(5);
  52. tree2.Insert(1);
  53. tree2.Insert(3);
  54. }
  55.  
  56. }
  57.  
  58. if (node == null)
  59. Root = newNode;
  60. else
  61. {
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement