Upload
marybeth-haynes
View
221
Download
0
Embed Size (px)
Citation preview
CSE 3358 NOTE SET 10
Data Structures and Algorithms
Complexity of Searching a Binary Tree
Worst Case: Linked List O(n)
Best Case: Complete Binary Tree O(lg n)
Average Case: Average Position in Average Tree O(lg n)
Tree Traversal
Process of visiting every node exactly one time No implied notion of order, so there are n! different
traversals Most are useless because
Depth-First Breadth-First
Depth First Searching
In – order Left Visit Right
Pre – Order Visit Left Right
Post – Order Left Right Visit
In - Order
template<class T>void BST<T>::inorder(BSTNode<T> *p) { if (p != 0) { inorder (p->left); visit(p); inorder (p->right); }}
13
10 25
2 12 20 31
293
In order Traversal:
Pre - Order
template<class T>void BST<T>::preorder(BSTNode<T> *p) { if (p != 0) { visit(p); preorder (p->left); preorder (p->right); }}
13
10 25
2 12 20 31
293
Pre order Traversal:
Post - Order
template<class T>void BST<T>::postorder(BSTNode<T> *p) { if (p != 0) { postorder (p->left); postorder (p->right); visit(p); }}
13
10 25
2 12 20 31
293
Post order Traversal:
Breadth-First Traversal
Visiting each node top-down-left-to-right Use a queue to store the children of a node when
the node is visited13
10 25
2 12 20 31
293
Breadth-First Traversal:
Breadth-First Traversal – Implementation Ideas
13
10 25
2 12 20 31
293
Breadth-First IMPL
template<class T>void BST<T>::breadthFirst(BSTNode<T> *p) { Queue<BSTNode<T>*> queue; BSTNode<T> *p = root; if (p != 0) { queue.enqueue(p); while(!queue.empty()) { p = queue.dequeue(); visit(p); if (p -> left != 0) queue.enqueue(p->left); if (p -> right != 0) queue.enqueue(p->right); } }}
To Recur or Not to Recur
template <class T>void BST<T>::iterativePreorder(){ Stack<BSTNode<T>*> travStack; BSTNode<T> *p = root; if (p != 0) { travStack.push(p); while(!travStack.empty()) { p = travStack.pop(); visit(p); if (p->right != 0) travStack.push(p->right); if (p->left != 0) travStack.push(p->left); } }}
Deleting
Three Cases:1) Node is a leaf
Set the pointer from the parent to null. release memory as appropriate.
2) Node has 1 child Set the pointer from the parent to the child of the node to
be deleted release memory as appropriate
3) Node has 2 children Will require multi-step process
Deleting: Case 1
13
10 25
2 12 20 31
293
Delete 3
Deleting: Case 2
13
10 25
2 12 20 31
293
Delete 31
Deleting: Case 3 – Option 1: Deleting by Merging
13
10 25
2 12 20 31
233
Delete 25
39
21 24
Find the right-most node of the left subtree
Make that node the parent of the right subtree (of the node to be deleted)
Deleting: Case 3 – Option 2: Deleting by Copying
13
10 25
2 12 20 31
233
Delete 25
39
21 24
Find the right-most node of the left subtree
Copy the key of that node to the node to be deleted.
Delete the node that was copied from.
?