BST operations

Search

public TreeNode search(TreeNode root, int target) {
	if (root == null || root.key == target) {
		return root;
	} else if (target < root.key) {
		return search(root.left);
	} else {
		return search(root.right);
	}
}
public TreeNode search(TreeNode root, int target) {
	while (root != null && root.key != target) {
		if (target < root.key) {
			root = root.left;
		} else {
			root = root.right;
		}
	}
	return root;
}

Insert

public TreeNode insert(TreeNode root, int target) {
	if (root == null) {
		return new TreeNode(target);
	}
	
	if (target < root.key) {
		root.left = insert(root.left, target);
	} else if (target > root.key) {
		root.right = insert(root.right, target);
	}
	return root;
}
public TreeNode insert(TreeNode root, int target) {
	TreeNode toInsert = new TreeNode(target);
	if (root == null) {
		return toInsert;
	}
	
	TreeNode prev = null, curr = root;
	while (curr != null) {
		prev = curr;
		if (curr.key == target) {
			return root;
		} else if (target < curr.key) {
			curr = curr.left;
		} else {
			curr = curr.right;
		}
	}
	if (target < prev.key) {
		prev.left = toInsert;
	} else {
		prev.right = toInsert;
	}
	return root;
}

Delete

public TreeNode delete(TreeNode root, int target) {
	if (root == null) {
		return null;
	}
	
	if (target < root.key) {
		root.left = delete(root.left, target);
		return root;
	} else if (target > root.key) {
		root.right = delete(root.right, target);
		return root;
	}
	
	if (root.left == null) {
		return root.right;
	}
	
	if (root.right == null) {	
		return root.left;
	}
	
	if (root.left.right == null) {
		root.left.right = root.right;
		return root.left;		
	}
	
	TreeNode prev = root.left, curr = prev.right;
	while (curr.right != null) {
		prev = curr;
		curr = curr.right;
	}
	prev.right = curr.left;
	
	curr.left = root.left;
	curr.right = curr.right;
	
	return curr;
}

Leave a comment