All pastes #367032 Raw Edit

Someone

public text v1 · immutable
#367032 ·published 2007-02-22 01:51 UTC
rendered paste body
public class BinaryTree {
	private Node root;
	
	public class Node {
		Node right;
		Node left;
		Comparable key;
		
		public Node(Comparable key) {
			right = null;
			left = null;
			this.key = key;
		}
	}
	
	public BinaryTree() {
	}
	
	public boolean search(Comparable key) {
	    return search(key, root);
	}
	
	private boolean search(Comparable key, Node currentNode) {
		if(currentNode != null) {
			if(key.compareTo(currentNode.key) == 0) {
				return true;
			} else if(currentNode.left != null && key.compareTo(currentNode.key) < 0) {
				return search(key, currentNode.left);
			} else  if(currentNode.right != null && key.compareTo(currentNode.key) > 0) {
				return search(key, currentNode.right);
			}	
		}
		return false;
	}
	
	public void insert(Comparable key) {
		insert(key, root);
	}
	
	private void insert(Comparable key, Node currentNode) {
		if(currentNode != null) {
			if(key.compareTo(currentNode.key) < 0) {
				if(currentNode.left != null) {
					insert(key, currentNode.left);
				} else {
					currentNode.left = new Node(key);
				}
			} else if(key.compareTo(currentNode.key) > 0) {
				if(currentNode.right != null) {
					insert(key, currentNode.right);
				} else {
					currentNode.right = new Node(key);
				}
			}				
		} else {
			currentNode = new Node(key);
		}
	}
	
	public int getElementCount() {
		return getElementCount(root);
	}
	
	private int getElementCount(Node currentNode) {
	    if (currentNode == null) {
	        return 0;
	    } else {
	        return 1 + getElementCount(currentNode.left) + getElementCount(currentNode.right);
	    }
	}
	
	public int getTreeHeight() {
		return 1+max(getTreeHeight(root.right),getTreeHeight(root.left));
	}
	
	private int getTreeHeight(Node currentNode) {
		if(currentNode == null) {
			return 0;
		} else {
			return 1+max(getTreeHeight(currentNode.left),getTreeHeight(currentNode.right));
		}
	}
	
	private int max(int a, int b) {
		if(a>b) {
			return a;
		} else if(b>a) {
			return b;
		}
		return a;
	}
	
	public int getLeafCount() {
		return getLeafCount(root);
	}
	
	private int getLeafCount(Node currentNode) {
		if(currentNode == null) {
			return 0;
		} else if(currentNode.left == null && currentNode.right == null) {
			return 1;
		}
		return getLeafCount(currentNode.left)+getLeafCount(currentNode.right);
	}
}