TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees version 1.0 Chapter Objectives  Learn about tree structures    Learn about how to implement tree structures     definition traversal operations linked.

Download Report

Transcript TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees version 1.0 Chapter Objectives  Learn about tree structures    Learn about how to implement tree structures     definition traversal operations linked.

TCSS 342, Winter 2006 Lecture Notes

Trees Binary Trees Binary Search Trees version 1.0

1

Chapter Objectives

   Learn about tree structures   definition traversal operations Learn about how to implement tree structures    linked structures simulated links using arrays computational strategy using arrays Learn about binary search trees 2

Trees

  A tree is a collection of nodes.

  The collection is either empty OR It consists of   a distinguished node r , called a root and zero or more non-empty distinct (sub)trees T 1 , … , T k , each of whose root are connected by a directed edge from r .

Represents commonly found hierarchical structure 3

figure 9.1

Tree terminology

4

Visualizing Trees

r

T 2 T 3 T 1   r root of each subtree is a child is the parent of r.

of each subtree root.

5

       

Tree terminology

A leaf has no children. An internal node Siblings has at least one child. have the same parent.

grandparent, grandchild, ancestor, descendant A path that n i is a sequence of nodes n 1 , n 2 , … is the parent of n i+1 for 1  i < k.

The length the path.

, n k such of a path is the number of edges in The depth of a node is the length of the path from the root to the node. (Starts at zero!) The height of a tree: length of the longest path from root to a leaf.

6

figure 9.2

Path length and level

7

Balanced and unbalanced trees

8

Tree example

C:\ tcss342 D101 hw1 hw2 one.java

test.java

proj1 calc.java

school MyMail pers 9

Trees are Everywhere

    family genealogy organizational charts    corporate government military folders/files on a computer compilers: parse tree a = (b + c) * d; a = + * d b c 10

Tree traversals

preorder traversal public void preorderPrintTree(TreeNode tnode){ tnode.print(); // preorder spot!

for each child c of tnode preorderPrintTree(c); } }  postorder traversal public void postorderPrintTree(TreeNode tnode){ for each child c of tnode postorderPrintTree(c); tnode.print(); // postorder spot!

11

Tree traversals

} 

postorder traversal node count.

public int numNodes(TreeNode tnode) { if (tnode == null) return 0; else { int sum = 0; for each child c of tnode sum += numNodes(c); return 1 + sum; } 12

Tree Implementation:First child/next sibling public class TreeNode { T element; TreeNode firstChild; TreeNode nextSibling; C:\ } tcss342 D101 MyMail hw1 one.java

hw2 test.java

proj1 calc.java

school pers 13

Level order traversal

• Stated in pseudocode, the algorithm for a level order traversal of a tree is: 14

Binary tree impl. with links

 A binary tree is a tree where all nodes have at most two children.

class BinaryTreeNode { T element; BinaryTreeNode left; BinaryTreeNode right; 1 } 2 1 3 4 2 3 5 6 4 5 6 7 7 15

BinaryTree constructors

public class BinaryTree { protected int count; protected BinaryTreeNode root; // Creates an empty binary tree.

public BinaryTree(){. . .} // Creates a binary tree with the specified element // as its root.

public BinaryTree (T element) { . . . } // Constructs a binary tree from the two specified // binary trees. public BinaryTree (T element, BinaryTree leftSubtree, BinaryTree rightSubtree) { . . .} 16

The operations on a binary tree

17

Simulated link strategy for array implementation of trees

18

Computational strategy for array implementation of trees

19

 

Binary Search Trees

Associated with each node is a key value that can be compared.

Binary search tree property:  every node in the left subtree has key whose value is less than the value of the root ’ s key value, and   every node in the right subtree has key whose value is greater than the value of the root ’ s key value.

the left subtree and the right subtree have the binary search tree property.

20

Example

5 4 8 1 7 3 BINARY SEARCH TREE 11 21

Counterexample

8 5 11 2 7 6 10 4 15 NOT A BINARY SEARCH TREE 18 20 21 22

additional binary search tree operations

23

find on binary search tree

 Basic idea: compare the value to be found to the key of the root of the tree.

 If they are equal, we are done.

 If they are not equal, recurse depending on which half of the tree the value to be found should be in if it is there.

T find(T target, BinaryTreeNode tn) { if (tn == null) return null; else if (target < tn.element) return find(target, tn.left); else if (target > tn.element) return find(target, tn.right); else return tn.element; // match } 24

Adding elements to a binary search tree

25

 

BST addElement

To addElement(), first find( ) its proper location, then insert() it.

This recursive implementation recurses down to null nodes, and returns a node which must be assigned to the parent. private BinaryTreeNode insert(T el, BinaryTreeNode tn){ if (tn == null) tn = new BinaryTreeNode(el, null, null); else if (el < tn.element) tn.left = insert(el, tn.left); else if (el > tn.element) tn.right = insert(el, tn.right); else ; // duplicate item; do appropriate thing return tn; } public void addElement(T el){ // you write this! // how would you call insert() here?

} 26

findMin, findMax

To find the maximum element in the BST, we follow right children until we reach NULL.

5 4 8 1 7 11 3  To find the minimum element in the BST, we follow left children until we reach NULL.

27

figure 10.4

Removing elements from a binary search tree

28

BST remove

   Removing an item disrupts the tree structure.

Basic idea:   find Then tree.

the node that is to be removed. “ fix ” the tree so that it is still a binary search  Remove node and replace it with its successor or predecessor (whichever more convenient) Three cases:    node has no children node has one child node has two children 29

1 3

No children, one child

5 4 8 5 7 1 11 4 3 8 7 11 30

1 

Two children

Replace the node with its successor. Then remove the successor from the tree.

7 5 4 8 4 8 1 7 7 11 3 3 11 31

 

Height of BSTs

n -node BST: Worst case depth: n-1 .

Claim: The maximum number of nodes in a binary tree of height h is 2 h +1 – 1.

Proof: The proof is by induction on h . For h the tree has one node, which is equal to 2 0+1 = 0, – 1.

Suppose the claim is true for any tree of height Any tree of height of height h has at most 2 (2 h +1 h h +1 has at most two subtrees – 1)+1 = 2 h +2 – 1.

. . By the induction hypothesis, this tree 32

Height of BSTs, cont

d

 If we have a BST of then by the Claim, n n  2 h +1 – 1.

So, h  log ( n +1) – 1.

nodes and height h , 33

Examining time complexity

  How long does it take to insert the items 1, 2, 3, … , n (in that order) into a BST?

What order would you insert items 1, 2, 3, this series of n inserts take? … , n into a BST so that it is perfectly balanced? How long would 34

Time Complexity

     A search, insertion, or removal, visits the nodes along a

to leaf path root-

Time O(1) is spent at each node The worst-case running time of each operation is O( is the height of the tree h ), where h With n -node binary tree, height is in n 1 in the worst case (when a binary search tree looks like a sorted sequence) To achieve good running time, we need to keep the tree

balanced

with O(log n) height 35

Average complexity

 Average depth of nodes in a tree. Assumptions: insert items randomly (with equal likelihood); each item is equally likely to be looked up.

 Average depth for log n n -node tree  1.442 36

References

  Lewis & Chase book, Chapter 12 & 13.

Rosen ’ s discrete math book also talks about trees in chapter 9.

37