Advertisement
Guest User

Untitled

a guest
Oct 12th, 2016
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.07 KB | None | 0 0
  1. class Node {
  2.     public int val;
  3.     public Node left;
  4.     public Node right;
  5.  
  6.     public Node(int val) {
  7.         this.val = val;
  8.     }
  9. }
  10.  
  11. class BinTree {
  12.     Node root;
  13.    
  14.     public BinTree() {
  15.         root = null;
  16.     }
  17.  
  18.     public void insert(int val) {
  19.         if (root == null) {
  20.             root = new Node(val);
  21.             return;
  22.         }
  23.         insert(val, root);
  24.     }
  25.  
  26.     private void insert(int val, Node node) {
  27.        if (val < node.val) {
  28.            if (node.left == null) {
  29.                node.left = new Node(val);
  30.                return;
  31.            }
  32.            insert(val, node.left);
  33.        }
  34.        else {
  35.            if(node.right == null) {
  36.                node.right = new Node(val);
  37.                return;
  38.            }
  39.            insert(val, node.right);
  40.        }
  41.     }
  42.  
  43.     public void print() {
  44.         print(root);
  45.     }
  46.  
  47.     private void print(Node node) {
  48.         if (node != null) {
  49.             print(node.left);
  50.             Console.WriteLine("{0}", node.val);
  51.             print(node.right);
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement