Skip to content

Instantly share code, notes, and snippets.

@gtke
Created January 28, 2013 18:52
Show Gist options
  • Select an option

  • Save gtke/4658034 to your computer and use it in GitHub Desktop.

Select an option

Save gtke/4658034 to your computer and use it in GitHub Desktop.
BST Traversal
/**
* Finds the in-order traversal of the BST
*
* @return A list of the data set in the BST in in-order
*/
public List<T> inOrder() {
List<T> list = new ArrayList<T>();
inOrder(root, list);
return list;
}
public void inOrder(Node<T> node, List<T> list){
if(node != null){
inOrder(node.left, list);
list.add(node.getData());
inOrder(node.right, list);
}
}
/**
* Finds the post-order traversal of the BST
*
* @return A list of the data set in the BST in post-order
*/
public List<T> postOrder() {
List<T> list = new ArrayList<T>();
postOrder(root, list);
return list;
}
public void postOrder(Node<T> node, List<T> list){
if(node != null){
postOrder(node.left, list);
postOrder(node.right, list);
list.add(node.getData());
}
}
/**
* Finds the pre-order traversal of the BST
*
* @return A list of the data set in the BST in pre-order
*/
public List<T> preOrder() {
List<T> list = new ArrayList<T>();
preOrder(root, list);
return list;
}
public void preOrder(Node<T> node, List<T> list) {
if(node != null){
list.add(node.getData());
preOrder(node.left,list);
preOrder(node.right,list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment