TCSS 342 Winter 2006 Lecture Notes Trees Binary
TCSS 342, Winter 2006 Lecture Notes Trees Binary Search Trees version 1. 0 1
Chapter Objectives n Learn about tree structures n n n Learn about how to implement tree structures n n definition traversal operations linked structures simulated links using arrays computational strategy using arrays Learn about binary search trees 2
Trees n A tree is a collection of nodes. n n The collection is either empty OR It consists of n n n a distinguished node r, called a root and zero or more non-empty distinct (sub)trees T 1, … , Tk, 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 1 n n T 3 root of each subtree is a child of r. r is the parent of each subtree root. 5
Tree terminology n n n n A leaf has no children. An internal node has at least one child. Siblings have the same parent. grandparent, grandchild, ancestor, descendant A path is a sequence of nodes n 1, n 2, … , nk such that ni is the parent of ni+1 for 1 i < k. The length of a path is the number of edges in the path. 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: hw 1 one. java hw 2 test. java My. Mail D 101 tcss 342 proj 1 school pers calc. java 9
Trees are Everywhere n n family genealogy organizational charts n n n corporate government military folders/files on a computer compilers: parse tree a = * a = (b + c) * d; + b d c 10
Tree traversals n preorder traversal public void preorder. Print. Tree(Tree. Node<T> tnode){ tnode. print(); // preorder spot! for each child c of tnode preorder. Print. Tree(c); } n postorder traversal public void postorder. Print. Tree(Tree. Node<T> tnode){ for each child c of tnode postorder. Print. Tree(c); tnode. print(); // postorder spot! } 11
Tree traversals postorder traversal node count. n public int num. Nodes(Tree. Node<T> tnode) { if (tnode == null) return 0; else { int sum = 0; for each child c of tnode sum += num. Nodes(c); return 1 + sum; } } 12
Tree Implementation: First child/next sibling public class Tree. Node<T> { T element; Tree. Node first. Child; Tree. Node next. Sibling; C: } tcss 342 hw 1 one. java hw 2 test. java My. Mail D 101 proj 1 school pers calc. java 13
Level order traversal • Stated in pseudocode, the algorithm for a level order traversal of a tree is: 14
Binary tree impl. with links n A binary tree is a tree where all nodes have at most two children. class Binary. Tree. Node<T> { T element; Binary. Tree. Node left; Binary. Tree. Node right; } 1 4 3 5 2 3 2 4 1 6 5 7 6 7 15
Binary. Tree constructors public class Binary. Tree<T> { protected int count; protected Binary. Tree. Node<T> root; // Creates an empty binary tree. public Binary. Tree(){. . . } // Creates a binary tree with the specified element // as its root. public Binary. Tree (T element) {. . . } // Constructs a binary tree from the two specified // binary trees. public Binary. Tree (T element, Binary. Tree<T> left. Subtree, Binary. Tree<T> right. Subtree) {. . . } 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 n n Associated with each node is a key value that can be compared. Binary search tree property: n n n 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 1 8 7 11 3 BINARY SEARCH TREE 21
Counterexample 8 5 2 7 4 11 6 10 18 15 NOT A BINARY SEARCH TREE 20 21 22
additional binary search tree operations 23
find on binary search tree n Basic idea: compare the value to be found to the key of the root of the tree. n n 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, Binary. Tree. Node 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 add. Element n n To add. Element(), 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 Binary. Tree. Node<T> insert(T el, Binary. Tree. Node tn){ if (tn == null) tn = new Binary. Tree. Node<T>(el, 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 add. Element(T el){ // you write this! // how would you call insert() here? 26
find. Min, find. Max n To find the maximum element in the BST, we follow right children until we reach NULL. 5 4 1 8 7 11 3 n 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 n n Removing an item disrupts the tree structure. Basic idea: n n find the node that is to be removed. Then “fix” the tree so that it is still a binary search tree. Remove node and replace it with its successor or predecessor (whichever more convenient) Three cases: n node has no children node has one child node has two children 29
No children, one child 5 4 8 5 1 7 3 11 1 4 8 7 11 3 30
Two children n Replace the node with its successor. Then remove the successor from the tree. 7 5 4 4 8 1 1 8 7 7 11 11 3 3 31
Height of BSTs n n 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 = 0, the tree has one node, which is equal to 20+1 – 1. Suppose the claim is true for any tree of height h. Any tree of height h+1 has at most two subtrees of height h. By the induction hypothesis, this tree has at most 2 (2 h+1 – 1)+1 = 2 h+2 – 1. 32
Height of BSTs, cont’d n If we have a BST of n nodes and height h, then by the Claim, n 2 h+1 – 1. So, h log (n+1) – 1. 33
Examining time complexity n n 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, …, n into a BST so that it is perfectly balanced? How long would this series of n inserts take? 34
Time Complexity n n n A search, insertion, or removal, visits the nodes along a root- to leaf path Time O(1) is spent at each node The worst-case running time of each operation is O(h), where h is the height of the tree 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 n n 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 n-node tree 1. 442 log n 36
References n n Lewis & Chase book, Chapter 12 & 13. Rosen’s discrete math book also talks about trees in chapter 9. 37
- Slides: 37