Binary Search Tree Algorithms

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Binary Search Tree Algorithms

Algorithm InsertBST (v, root) Iteratively insert a value v into a binary search tree (BST) with root named root. if root is empty then root v; else node root; loop {an innite loop; we will explicitly exit the loop after v is inserted} if v value stored in node then if the left child of node exists then node left child of node; else insert v as the left child of node; exit the loop; end if else if the right child of node exists then node right child of node; else insert v as the right child of node; exit the loop; end if end if end loop end if

Algorithm InsertBST (v, root) Recursively insert a value v into a binary search tree (BST) with root named root. if root is empty then root v; else if v value stored in root then if the left child of root exists then InsertBST (v, left child of root); else insert v as the left child of root; end if else if the right child of root exists then InsertBST (v, right child of root); else insert v as the right child of root; end if end if end if

Algorithm CreateBST (A) Create a binary search tree (BST) from an array A with N elements. root the root of a new binary search tree named T ; index 1; while index N do InsertBST (A[index ], root); index index + 1; end while return T

Algorithm InOrder (root) Perform an inorder (second-visit) traversal of the BST with root named root. if root is empty then return else InOrder (left child of root); output the value in root; InOrder (right child of root); end if

Algorithm TreeSort (A) Sort the elements in array A using a binary search tree (BST). CreateBST (A); {Creates a new BST T containing the elements of A} InOrder (root of T ); {Sorts the elements in T using an inorder traversal}

You might also like