35
trees 1 Binary Trees Binary Trees

trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

  • View
    221

  • Download
    2

Embed Size (px)

Citation preview

Page 1: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 1

Binary TreesBinary Trees

Page 2: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 2

Basic terminologyBasic terminology

• Finite set of nodesnodes (may be empty -- 0 nodes), which contain data

• First node in tree is called the rootroot

Page 3: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 3

Basic terminologyBasic terminology

• Each node may be linked to 0, 1 or 2 child nodeschild nodes (or childrenchildren)

• A node with children is a parentparent; a node with no children is a leafleaf

Nodes d and e are children of bNode c is parent of f and g

Page 4: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 4

More botany & sociologyMore botany & sociology

• The root node has no parent; it is the ancestorancestor of all other nodes

• All nodes in the tree are descendantsdescendants of the root node

• Nodes with the same parent are siblingssiblings

• Any node with descendants (any parent node) is the root node of a subtreesubtree

Page 5: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 5

But wait, there’s more!But wait, there’s more!

• Tree depthdepth is the maximum number of steps through ancestor nodes from the deepest leaf back to root– tree with single node (root)

has depth of 0– empty tree has depth of -1

Depth of entire treeis 2; depth of b’s subtree is 1; depth of f’ssubtree is 0

Page 6: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 6

Tree shape terminologyTree shape terminology

• FullFull binary tree– every parent has 2

children,– every leaf has equal

depth

Page 7: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 7

Tree shape terminologyTree shape terminology

• CompleteComplete binary tree– every level is full

except possibly the deepest level

– if the deepest level isn’t full, leaf nodes are as far to the left as possible

Page 8: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 8

Some examplesSome examples

Completebinary tree

Full andcomplete

Neither fullnor complete

Complete

Neither

Both

Page 9: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 9

Array representation of a binary treeArray representation of a binary tree

• Complete binary tree is easily represented as an array (either static or dynamic)

• Root data is stored at index 0

• Root’s children are stored at index 1 and 2

A B C

A

B C

Page 10: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 10

Array representation of a binary treeArray representation of a binary tree

• In general:– root is tree[0]– for any node at tree[n], the parent node will be

found at index (n-1)/2– for any node at tree[n], the children of n (if any)

will be found at tree[2n + 1] and tree[2n + 2]

Page 11: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 11

Array representation of a binary treeArray representation of a binary tree

• Since these formulas apply to any complete tree represented as an array, can create a tree class with 2 private members:– an array that stores the data– a counter to keep track of the number of nodes

in the tree

• Relationships between nodes can always be determined from the given formulas

Page 12: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 12

Binary tree with array Binary tree with array representationrepresentation

template <class item>class binTree{

...private:

Item* root;int used;int capacity;

}

Private member root represents container -root is a pointer to adynamic array of Items

Private member used represents number ofvalues currently stored in tree; capacity is currentmaximum number of values that can be stored

Page 13: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 13

Binary tree with array Binary tree with array representationrepresentation

• Choice of member functions for binary tree would depend on application

• Later on, we’ll look at the heap data structure, which is a binary tree based on an array representation

Page 14: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 14

Array representation of a binary treeArray representation of a binary tree

• What if tree isn’t complete?– Can still use array, but problem is more

complicated -- have to keep track of which children actually exist

– One possibility would be to place a known dummy value in empty slots

– Another is to add another private member to the class -- an array of bools paired to the data array -- index value is true if data exists, false if not

Page 15: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 15

Linked representation of binary treeLinked representation of binary tree

• Again, as with linked list, entire tree can be represented with a single pointer -- in this case, a pointer to the root node

• Nodes are instances of class BTnode, described in the next several slides

• The class contains functions that operate on single nodes; we will also look at non-member functions that perform tree operations

Page 16: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 16

template <class Item>

class BTnode

{ …

private:

Item data;

BTnode *left;

BTnode *right;

};

Linked representation of binary treeLinked representation of binary tree

Private memberdata holds theinformation in thenode; membersleft and right arepointers to the node’s left and right children

Page 17: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 17

Functions of BTnode classFunctions of BTnode class

• Constructor: creates node with specified data and left and right children

• Observer functions– data() returns value of data member– get_left() returns pointer to left child– get_right() returns pointer to right child– is_leaf() returns true if node is a leaf

Page 18: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 18

Functions of BTnode classFunctions of BTnode class

• Modifiers– set_data(): changes data portion of node– set_left(): assigns new left child to node– set_right(): assigns new right child to node– modifier versions of get_data(), get_left() and

get_right()

Page 19: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 19

Non-member functionsNon-member functions

• Observers (entire tree)– tree_size() returns number of nodes in tree– traversal functions (preorder(), inorder() and

postorder()) provide different methods for moving through and processing all nodes of a tree or subtree

– print() function uses traversal to print values of data portions of all nodes in a tree shape

Page 20: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 20

Non-member functionsNon-member functions

• Modifiers (entire tree):– tree_clear(): return memory occupied by an

entire tree or subtree to system heap– tree_copy(): returns pointer to a node that is the

root of an exact copy of the tree passed to the function as a parameter

Page 21: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 21

BTnode classBTnode class{ public:

BTnode (const Item& entry = Item(),BTnode* L = NULL, BTnode* R = NULL);

const Item& data( ) const {return data;} const BTnode* get_left( )const {return left;} const BTnode* get_right( )const {return right;} bool is_leaf( ) const {return (left == NULL) && (right == NULL);} …

Page 22: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 22

Default constructorDefault constructor

template <class Item>BTnode::BTnode(const Item& entry,

BTnode* L, BTnode* R){data = entry;left = L;right = R;

}

Page 23: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 23

BTnode class definition continuedBTnode class definition continued

… Item& data( ) { return data; } Btnode* get_left( ) { return left; } Btnode* get_right( ) { return right; } void set_data(const Item& it) { data = it; } void set_left( BTnode* L) { left = L; } void set_right( BTnode* R) { right = R; } …

Page 24: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 24

Non-member functionsNon-member functions

void tree_clear ( Btnode& root);

Btnode* tree_copy (const Btnode & root);

Page 25: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 25

Function tree_clear( )Function tree_clear( )

• Good example of a function in which a recursive solution is the simplest and most elegant method

• Base case: root is NULL (function does no work)• Problem reduction:

– clear left subtree (recursive call)– clear right subtree (recursive call)

• To finish: – return root’s memory to heap– set root to NULL

Page 26: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 26

Function tree_clear( )Function tree_clear( )

template <class Item>void tree_clear(BTnode<Item>*& root){if (root != NULL){

tree_clear(root->left);tree_clear(root->right);delete root;root = NULL;

}}

Page 27: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 27

Tree_clear in actionTree_clear in action

Original tree:

Page 28: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 28

Tree_clear in actionTree_clear in action

Since root is not NULL,proceed recursivelydown left subtree untila NULL pointer isencountered

Page 29: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 29

Tree_clear in actionTree_clear in action

This node’s left pointeris NULL; so recursionstops here, and mostrecent call to functionreturns with call totree_clear(root->right)

Since this node’s right pointer is alsoNULL, this recursivecall returns, and weproceed to next line:

delete root;followed by:

root = NULL;

Page 30: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 30

Tree_clear in actionTree_clear in action

The function then returns,and the same processis repeated at eachsubtree in root’sleft subtree

Page 31: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 31

Tree_clear in actionTree_clear in action

The same process takesplace in the right subtree

Page 32: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 32

Tree_clear in actionTree_clear in action

Finally, only root is left:

Page 33: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 33

Function tree_copy( )Function tree_copy( )

• Copying a tree is also a recursive function• Goal is to return a pointer to a tree that is an exact

copy of the tree referenced by the source root pointer

• Base case: source root is NULL (return NULL)• Recursive calls: call copy function on source root’s

left & right subtrees• Final step: use constructor to create new root pointer

Page 34: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 34

template <class Item>BTnode<Item>* tree_copy(const BTtnode<Item>*

root){

BTnode<Item> *lp;BTnode<Item> *rp;if (root == NULL)

return NULL;else{

lp = tree_copy(root->left);rp = tree_copy(root->right);return new BTnode<Item> (root->data,

lp, rp);}

}

Page 35: trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called

trees 35

Binary TreesBinary Trees

- ends -