CS226 -- Day 16 -- Spring 2013 Recursive tree definition: a linked structure of (sub)trees in TreeRoot.java Binary Trees ======================================================= - every node has at most 2 children (called left & right usually) - depth-first traversals: - pre-order: root, left (recurse), right (recurse) - post-order: left (recurse), right (recurse), root - in-order: left (recurse), root, right (recurse) Example/application: arithmetic expression evaluation Consider this arithmetic expression: (1+2) * -6 - 2 * (14/5) This binary tree represents it and can be used to compute the result: - / \ * * / \ / \ + - 2 / / \ \ / \ 1 2 6 14 5 in-order traversal for fully parenthesized in-fix form: (((1+2)*(-6))-(2*(14/5))) pre-order traversal generates pre-fix notation: - * + 1 2 - 6 * 2 / 14 5 post-order traversal generates post-fix notation: 1 2 + 6 - * 2 14 6 / * - Binary Tree Properties ============================================ - every node has at most 2 children - assume n nodes, height h: h < n log n <= h because n <= 2^(h+1) - 1 = sum (i=0,h) 2^i #nodes at depth i <= 2^i Proper Binary Tree: all nodes have 0 or 2 children Complete Binary Tree: full from top to bottom, left to right h <= log n (+ 1)? Balanced Binary Tree: difference in height of left and right subtrees is at most 1 Binary Tree Implementations ====================================== Recursive Linked Structure: Bnode has T data, Bnode parent, Bnode left, Bnode right Ranked Sequence Representation: use array, waste slot at index 0 root goes into index 1 left child of node at i is at index 2i right child of node at i is at index 2i+1 parent of node at i is at index i/2 (integer division) 1 / \ 2 3 / / \ 4 6 7 / \ / \ \ 8 9 12 13 15 Binary Search Tree (BST) - used for ordered data ======================== Critical BST Properties - everything in left subtree of node is < node - everything right subtree of node is >= node (really, you can decide which side to put the = values, if permitted) - inorder traversal gives nodes in sorted order! - this is not necessarily proper or complete - find method is O(h) where h is height of tree - remember: log n <= h <= n - insertion is O(h) - search down tree to external node where it belongs, add - removal (close up holes) is O(h) - if has one child, move child node in to take it's place - if has 2 children, find prev or next node in inorder traversal, this must be external or have 1 child, replace examples - create the following binary search trees: (try using http://www.iu.hio.no/~ulfu/AlgDat/applet/binarytreesome2.html) insert: 1 3 5 7 9 2 4 6, skewed to right insert: 5 3 7 1 9, nicely balanced insert: 7 2 13 4 5 15 12 17 now delete these: 5 2 13