Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Binary trees

2,381 views

Published on

Published in: Education, Technology, Business
  • Be the first to comment

  • Be the first to like this

Binary trees

  1. 1. Binary TreesBinary Trees Chapter 6Chapter 6
  2. 2. Linked Lists SuckLinked Lists Suck  By now you realize that the title to this slide isBy now you realize that the title to this slide is true…true…  When we are talking about searching orWhen we are talking about searching or representing data structures that need arepresenting data structures that need a hierarchical structures.hierarchical structures.  We need a better structure…We need a better structure…  So we get binary treesSo we get binary trees
  3. 3. Tree definitionTree definition  Here is a (recursive, of course) definition forHere is a (recursive, of course) definition for a tree:a tree: 1.1. An empty structure is an empty treeAn empty structure is an empty tree 2.2. If t1,…,tk are disjointed trees, then theIf t1,…,tk are disjointed trees, then the structure whose root has as its children thestructure whose root has as its children the roots of t1,…,tk is also a treeroots of t1,…,tk is also a tree 3.3. Only structures generate by rules 1 and 2 areOnly structures generate by rules 1 and 2 are trees.trees.
  4. 4. More terminologyMore terminology  Each node has to be reachable from the rootsEach node has to be reachable from the roots through a unique sequence of arcs called athrough a unique sequence of arcs called a path.path.  The number of arcs in a path is called theThe number of arcs in a path is called the length of the path.length of the path.  The level of a node is the length of the pathThe level of a node is the length of the path from the root to the node plus 1.from the root to the node plus 1.  The height of a non-empty tree is theThe height of a non-empty tree is the maximum level of a node in the tree.maximum level of a node in the tree.
  5. 5. Special TreesSpecial Trees  An empty tree has a height of zero.An empty tree has a height of zero.  A single node tree is a tree of height 1.A single node tree is a tree of height 1.  This is the only case where a node is both a rootThis is the only case where a node is both a root and a leaf.and a leaf.
  6. 6. Binary TreesBinary Trees  According to the definition of trees, a node canAccording to the definition of trees, a node can have any number of children.have any number of children.  A binary tree is restricted to only having 0, 1,A binary tree is restricted to only having 0, 1, or 2 children.or 2 children.  A complete binary tree is one where all theA complete binary tree is one where all the levels are full with exception to the last levellevels are full with exception to the last level and it is filled from left to right.and it is filled from left to right.  A full binary tree is one where if a node has aA full binary tree is one where if a node has a child, then it has two children.child, then it has two children.
  7. 7. Full Binary Tree TheoremFull Binary Tree Theorem  For all the nonempty binary trees whoseFor all the nonempty binary trees whose nonterminal node have exactly two nonemptynonterminal node have exactly two nonempty children, the number of leaveschildren, the number of leaves mm is greateris greater than the number of nonterminal nodethan the number of nonterminal node kk andand mm == kk + 1.+ 1.
  8. 8. Binary Search TreesBinary Search Trees  A binary search tree (BST) is a binary tree thatA binary search tree (BST) is a binary tree that has the following property: For each nodehas the following property: For each node nn ofof the tree, all values stored in its left subtree arethe tree, all values stored in its left subtree are less than valueless than value vv stored instored in nn, and all values, and all values stored in the right subtree are greater thanstored in the right subtree are greater than vv..  This definition excludes the case of duplicates.This definition excludes the case of duplicates. They can be include and would be put in theThey can be include and would be put in the right subtree.right subtree.
  9. 9. Binary Tree TraversalsBinary Tree Traversals  A traversal is where each node in a tree isA traversal is where each node in a tree is visited and visited oncevisited and visited once  For a tree of n nodes there are n! traversalsFor a tree of n nodes there are n! traversals  Of course most of those are hard to programOf course most of those are hard to program  There are two very common traversalsThere are two very common traversals  Breadth FirstBreadth First  Depth FirstDepth First
  10. 10. Breadth FirstBreadth First  In a breadth first traversal all of the nodes on aIn a breadth first traversal all of the nodes on a given level are visited and then all of the nodesgiven level are visited and then all of the nodes on the next level are visited.on the next level are visited.  Usually in a left to right fashionUsually in a left to right fashion  This is implemented with a queueThis is implemented with a queue
  11. 11. Depth FirstDepth First  In a depth first traversal all the nodes on aIn a depth first traversal all the nodes on a branch are visited before any others are visitedbranch are visited before any others are visited  There are three common depth first traversalsThere are three common depth first traversals  InorderInorder  PreorderPreorder  PostorderPostorder  Each type has its use and specific applicationEach type has its use and specific application
  12. 12. InsertionInsertion  In order to build a tree you must be able toIn order to build a tree you must be able to insert into the treeinsert into the tree  In order to do this you need to know where theIn order to do this you need to know where the nodes goesnodes goes  Typically the tree is searched looking for aTypically the tree is searched looking for a null pointer to hang the new element fromnull pointer to hang the new element from  There are two common ways to do thisThere are two common ways to do this  Use a look ahead or check for null as the firstUse a look ahead or check for null as the first line in the codeline in the code
  13. 13. More insertionMore insertion  I prefer to check for null as the first thing I doI prefer to check for null as the first thing I do in my codein my code  It simplifies some of the testsIt simplifies some of the tests  And makes for a really easy to check for baseAnd makes for a really easy to check for base casecase
  14. 14. CodeCode InsertionHelper( Node *n, T data )InsertionHelper( Node *n, T data ) {{ if ( node == 0 )if ( node == 0 ) return new Node( data );return new Node( data ); if ( n->getData() < data )if ( n->getData() < data ) setLeft( InsertionHelper( n->getLeft(), data);setLeft( InsertionHelper( n->getLeft(), data); elseelse setRight( InsertionHelper( n->getRight(), data);setRight( InsertionHelper( n->getRight(), data); }}
  15. 15. DeletionDeletion  Deletion poses a bigger problemDeletion poses a bigger problem  When we delete we normally have two choicesWhen we delete we normally have two choices  Deletion by mergingDeletion by merging  Deletion by copyingDeletion by copying
  16. 16. Deletion by MergingDeletion by Merging  Deletion by merging takes two subtrees andDeletion by merging takes two subtrees and merges them together into one treemerges them together into one tree  The idea is you have a node n to deleteThe idea is you have a node n to delete  N can have two childrenN can have two children  So you find the smallest element in n’s leftSo you find the smallest element in n’s left subtreesubtree  You then take n’s right subtree and merge it toYou then take n’s right subtree and merge it to the bottom of the left subtreethe bottom of the left subtree  The root of the left subtree replaces nThe root of the left subtree replaces n
  17. 17. Deletion by copyingDeletion by copying  This will simply swap values and reduce aThis will simply swap values and reduce a difficult case to an easier onedifficult case to an easier one  If the node n to be deleted has no children,If the node n to be deleted has no children,  easy blow it awayeasy blow it away  If it has one childIf it has one child  Easy simply pass n’s child pointer up, make n’sEasy simply pass n’s child pointer up, make n’s parent point to n’s child and blow n awayparent point to n’s child and blow n away  If n has two child,If n has two child,  Now we have deletion by copyingNow we have deletion by copying
  18. 18. DetailsDetails  We find the smallest value in n’s right subtreeWe find the smallest value in n’s right subtree  We will take the value from that node and putWe will take the value from that node and put it in place of the value in nit in place of the value in n  We will then blow away the node that had theWe will then blow away the node that had the smallest value in itsmallest value in it

×