Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Tree Implementation. Binary Search Trees (BST) Nodes in Left subtree has smaller values Nodes in right subtree has bigger values.

Similar presentations


Presentation on theme: "Binary Tree Implementation. Binary Search Trees (BST) Nodes in Left subtree has smaller values Nodes in right subtree has bigger values."— Presentation transcript:

1 Binary Tree Implementation

2 Binary Search Trees (BST) Nodes in Left subtree has smaller values Nodes in right subtree has bigger values

3 Implementing Binary Trees Can be implemented in at least 2 ways – As linked structures – As arrays

4

5 BST – Linked List Vstion template class BSTNode { public: BSTNode() { left = right = 0; } BSTNode(const T& el, BSTNode *l = 0, BSTNode *r = 0) { key = el; left = l; right = r; } T key; BSTNode *left, *right; }; template class BST { ….//methods protected: BSTNode * root; …//methods }

6 Searching a BST For every node, compare the key to be located with the value stored in the node currently pointed at – If the key is less than the value, go to the left subtree and try again – If the key is greater than the value, try the right subtree – If the key is the same as the value, obviously the search stops

7 Searching a BST (cont’d) Example: Search for the key 15

8 Recursive version of search? Remember when to stop!

9 Tree Traversal Tree traversal is the process of visiting each node in the tree exactly one time – This definition does not specify the order in which the nodes are visited – For a tree with n nodes, how many different traversals there are? n! different traversals, but most of them are useless – Two main traversals: Breadth-First Depth-First

10 Breadth-First Traversal Visits each node starting from the lowest level and moving down level by level, visiting nodes on each level from left to right

11 DO 6.6 (c) (IN CLASS)

12 Depth-First Traversal Proceeds as far as possible to the left then backs up until the first crossroad, goes one step to the right, and again as far as possible to the left This process is repeated until all nodes are visited This definition does not specify exactly when nodes are visited: before proceeding down the tree or after backing up? – Preorder traversal – Inorder traversal – Postorder traversal

13 Inorder Traversal Left child, parent node, right child

14 Inorder Traversal (cont’d)

15 Run-Time Stack example

16 Preorder Traversal Parent node, left child, right child

17 Postorder Traversal Left child, right child, parent node

18


Download ppt "Binary Tree Implementation. Binary Search Trees (BST) Nodes in Left subtree has smaller values Nodes in right subtree has bigger values."

Similar presentations


Ads by Google