binary tree in csharp

Here is a simple implementation of a binary tree in C#:

main.cs
class Node {
    public int value;
    public Node left;
    public Node right;

    public Node(int value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

class BinaryTree {
    public Node root;

    public BinaryTree() {
        this.root = null;
    }

    public void Insert(int value) {
        Node newNode = new Node(value);

        if (root == null) {
            root = newNode;
        }
        else {
            Node temp = root;

            while (temp != null) {
                if (value < temp.value) {
                    if (temp.left == null) {
                        temp.left = newNode;
                        break;
                    }
                    else {
                        temp = temp.left;
                    }
                }
                else if (value > temp.value) {
                    if (temp.right == null) {
                        temp.right = newNode;
                        break;
                    }
                    else {
                        temp = temp.right;
                    }
                }
                else {
                    break;
                }
            }
        }
    }

    public void TraverseInOrder(Node node) {
        if (node != null) {
            TraverseInOrder(node.left);
            Console.Write(node.value + " ");
            TraverseInOrder(node.right);
        }
    }

    public void TraversePreOrder(Node node) {
        if (node != null) {
            Console.Write(node.value + " ");
            TraversePreOrder(node.left);
            TraversePreOrder(node.right);
        }
    }

    public void TraversePostOrder(Node node) {
        if (node != null) {
            TraversePostOrder(node.left);
            TraversePostOrder(node.right);
            Console.Write(node.value + " ");
        }
    }
}
1878 chars
79 lines

This implementation includes the Node class and the BinaryTree class. The Node class defines the structure of a node in the binary tree. The BinaryTree class includes methods to insert a new node into the tree and to traverse the tree in in-order, pre-order, and post-order.

To use this implementation, create a new instance of the BinaryTree class and use the Insert method to add new nodes. Then, use the TraverseInOrder, TraversePreOrder, and TraversePostOrder methods to print the node values in the desired order.

gistlibby LogSnag