



















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!




















2 Tree : recursive data structure (similar to list) Each cell may have zero or more successors (children) Each cell has exactly one predecessor (parent) except the root , which has none All cells are reachable from root Binary tree : tree in which each cell can have at most two children: a left child and a right child 5 4 7 8 9 2 General tree 5 4 7 8 2 Binary tree 5 4 7 8 Not a tree 5 6 8 List-like tree
class TreeCell
Most languages (natural and computer) have a recursive, hierarchical structure This structure is implicit in ordinary textual representation Recursive structure can be made explicit by representing sentences in the language as trees: Abstract Syntax Trees (ASTs) ASTs are easier to optimize, generate code from, etc. than textual representation A parser converts textual representations to AST 7
8
(^2 3 5 )
Text AST Representation
10 /** Return true iff x if the datum in a cell of tree node */ public static boolean treeSearch(Object x, TreeCell node) { if (node == null) return false; if (node.datum.equals(x)) return true; return treeSearch(x, node.left) || treeSearch(x, node.right); } 9 8 3 5 7 2 0 Analog of linear search in lists: given tree and an object, find out if object is stored in tree Easy to write recursively, harder to write iteratively
11
13
jan feb mar apr may jun jul
14
16 // Return true iff a node is a leaf public static boolean isLeaf(TreeCell node) { return (node != null) && (node.left == null) && (node.right == null); } //Return the height of a node using postorder traversal public static int height(TreeCell node) { if (node == null) return - 1; //empty tree if (isLeaf(node)) return 0; return 1 + Math.max(height(node.left), height(node.right)); } // Return number of nodes using postorder traversal public static int nNodes(TreeCell node) { if (node == null) return 0; return 1 + nNodes(node.left) + nNodes(node.right); }
19 jan feb mar apr jun may jul
20