Binary Search Trees
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
Using a Linked Structure
A preorder traversal of this BST will print the values in the nodes in the following order: 23, 15, 8, 12, 25, 24
A postorder traversal of this BST will print the values in the nodes in the following order: 12, 8, 15, 24, 25, 23
search(current, target) { if (current == null) print("Not present!") else if (current's data == target) print("Found!") else if (current's data >target) search(current's left, target) else search(current's right, target) }
search(current, target { while ( (current != null) && (current's data != target) ) { if (current's data > target) current = current's left else current = current's right } if (current's data == target) print("Found!") else print("Not present!") }
root
the new node
insert(current, n) { if (current == null) current = n; else if (n's data < current's data) insert(current's left, n) else if (n's data > current's data) insert(current's right, n) else print("Duplicate!") }
null