Problem:
For a Binary Search Tree, insert a node.
class BinarySearchTree<T extends Comparable<T>> { Node<T> root; public BinarySearchTree(Node<T> root) { this.root = root; } public void insert(T value) { insert(root, value); } private void insert(Node<T> node, T value) { if (value.compareTo(node.getValue()) < 0) { if (node.getLeft() != null) { insert(node.getLeft(), value); } else { node.setLeft(new Node<T>(value)); } } else if (value.compareTo(node.getValue()) > 0) { if (node.getRight() != null) { insert(node.getRight(), value); } else { node.setRight(new Node<T>(value)); } } } }
No comments:
Post a Comment