


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



! Note: subtree can start at any node ! There’s a subtree rooted at C! ! Subtrees follow same rules as trees ! A tree’s height is the largest number of nodes from root to leaf ! Height of the tree on the right is 4 (A->C->D->F) ! Balanced binary tree ! For all nodes, the height of the left and right subtree differ by at most 1 ! This tree is not balanced! ! Full tree ! No missing nodes ! For all nodes, height of left and right subtree are equal
CMPS 12B, UC Santa Cruz Trees, Trees, Trees 3
! TreeNode: an individual node in the tree ! BinaryTree: a subtree rooted at a particular TreeNode
! TreeNode (Object newItem) ! TreeNode (Object newItem, TreeNode lt, TreeNode rt) ! Object getItem() ! void setItem (Object newItem) ! TreeNode getLeft/Right() ! TreeNode setLeft/Right (TreeNode left) ! Note: this implementation doesn’t have “up” pointers in each node that point to the node’s parent
! Similar to operations in linked lists
! BinaryTree(): creates an empty tree ! BinaryTree(Object rootItem): creates a tree with a root ! BinaryTree(Object root, BinaryTree lt, BinaryTree rt): creates a tree with a root and left & right subtrees
! attachLeft/Right (Object newItem): attach an object to the left or right of the root ! attachLeft/RightSubtree (BinaryTree tree): attach an entire tree to the root ! attachLeft() could be done by creating a new subtree and attaching it with attachLeftSubtree()…
! Non-existent root ! Trying to attach something on top of an existing subtree
CMPS 12B, UC Santa Cruz Trees, Trees, Trees 7
! Trees can be traversed in three orders ! Pre-order: L, R, root ! B, F, D, E, C, A ! In-order: L, root, R ! B, A, F, D, C, E ! Post-order: root, L, R ! A, B, C, D, F, E ! Order chosen depends on ! What the tree is being used for ! What the traversal is supposed to accomplish ! Traversal is done recursively! ! Treat L, R as trees in their own right ! Recursively visit them