1 / 37

TCSS 342, Winter 2006 Lecture Notes

TCSS 342, Winter 2006 Lecture Notes. Trees Binary Trees Binary Search Trees. 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

Télécharger la présentation

TCSS 342, Winter 2006 Lecture Notes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. TCSS 342, Winter 2006Lecture Notes Trees Binary Trees Binary Search Trees version 1.0

  2. 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

  3. Trees • A tree is a collection of nodes. • The collection is either empty OR • It consists of • a distinguished noder, called a root and • zero or more non-empty distinct (sub)trees T1, … , Tk, each of whose root are connected by a directed edge from r. • Represents commonly found hierarchical structure

  4. figure 9.1 Tree terminology

  5. r T2 T3 T1 Visualizing Trees • root of each subtree is a child of r. • r is the parent of each subtree root.

  6. Tree terminology • 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 n1, n2, … , 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.

  7. figure 9.2 Path length and level

  8. Balanced and unbalanced trees

  9. C:\ MyMail tcss342 D101 school pers hw1 hw2 proj1 one.java calc.java test.java Tree example

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

  11. Tree traversals • preorder traversal public void preorderPrintTree(TreeNode<T> tnode){ tnode.print(); // preorder spot! for each child c of tnode preorderPrintTree(c); } • postorder traversal public void postorderPrintTree(TreeNode<T> tnode){ for each child c of tnode postorderPrintTree(c); tnode.print(); // postorder spot! }

  12. Tree traversals • postorder traversal node count. public int numNodes(TreeNode<T> tnode) { if (tnode == null) return 0; else { int sum = 0; for each child c of tnode sum += numNodes(c); return 1 + sum; } }

  13. C:\ MyMail tcss342 D101 school pers hw1 hw2 proj1 one.java test.java calc.java Tree Implementation:First child/next sibling public class TreeNode<T> { T element; TreeNode firstChild; TreeNode nextSibling; }

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

  15. 1 2 1 3 2 3 4 4 5 6 7 5 6 7 Binary tree impl. with links • A binary tree is a tree where all nodes have at most two children. class BinaryTreeNode<T> { T element; BinaryTreeNode left; BinaryTreeNode right; }

  16. BinaryTree constructors public class BinaryTree<T> { protected int count; protected BinaryTreeNode<T> 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<T> leftSubtree, BinaryTree<T> rightSubtree) { . . .}

  17. The operations on a binary tree

  18. Simulated link strategy for array implementation of trees

  19. Computational strategy for array implementation of trees

  20. 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.

  21. 5 4 8 1 7 11 3 Example BINARY SEARCH TREE

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

  23. additional binary search tree operations

  24. 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 }

  25. Adding elements to a binary search tree

  26. 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<T> insert(T el, BinaryTreeNode tn){ if (tn == null) tn = new BinaryTreeNode<T>(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? }

  27. 5 4 8 1 7 11 3 findMin, findMax • To find the maximum element in the BST, we follow right children until we reach NULL. • To find the minimum element in the BST, we follow left children until we reach NULL.

  28. figure 10.4 Removing elements from a binary search tree

  29. BST remove • Removing an item disrupts the tree structure. • Basic idea: • 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: • node has no children • node has one child • node has two children

  30. 5 4 8 1 7 11 3 5 4 8 1 7 11 3 No children, one child

  31. 5 4 8 1 7 11 3 7 4 8 1 7 11 3 Two children • Replace the node with its successor. Then remove the successor from the tree.

  32. 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 2h+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(2h+1– 1)+1 = 2h+2– 1.

  33. Height of BSTs, cont’d • If we have a BST of n nodes and height h, then by the Claim, n 2h+1– 1. So, h log (n+1) – 1.

  34. 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, …, n into a BST so that it is perfectly balanced? How long would this series of n inserts take?

  35. Time Complexity • 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-1in 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

  36. 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 n-node tree  1.442 log n

  37. References • Lewis & Chase book, Chapter 12 & 13. • Rosen’s discrete math book also talks about trees in chapter 9.

More Related