90 likes | 209 Views
CS 280 Data Structures. Professor John Peterson. Trees. The final “big topic” will be trees. We won’t be as worried about algorithms – we’ll be addressing the basic programming issues associated with tree-like structures. Expect lots of generics and lots of coding. Where Are The Trees?.
E N D
CS 280Data Structures Professor John Peterson
Trees The final “big topic” will be trees. We won’t be as worried about algorithms – we’ll be addressing the basic programming issues associated with tree-like structures. Expect lots of generics and lots of coding.
Where Are The Trees? • XML is a tree-based data language • File systems are trees • Program syntax is expressed in trees • Trees hide in many efficient data structures Our goal is to understand common patterns in tree-based program constructions
Tree Terminology • Root: the “topmost” node in the tree • Node / subtree: an element of the tree • Leaf: a node in the tree that has no subnodes • Height / Depth: deals with the distance to the root • Branch: a node with others below • Binary tree: a tree in which every node has at most 2 subtrees, called “left” and “right”. • N-ary tree: one in which a node as an arbitrary (ordered) number of subtrees
Binary Trees vs N-ary Trees A binary tree is the easiest to represent. Usually n-ary trees are more realistic. We’ll start with binary trees though since that’s simpler. I’ll be lecturing using straight binary and let you implement n-ary in the homework.
A Binary Tree Type class BTree<T> { public BTree<T> left; public BTree<T> right; public T data; public Tree(T data) { this.data = data; this.left = null; this.right = null; // Add a similar one for initializing all three fields
Tree Operations There are a LOT of operators we can define on trees. But we should start with the basics: reading and printing. Without these we can’t do any unit testing. There are lots of ways to display a tree: • Briefly (use the object hash here) • Pretty (nice indentation) • Compact (big string – good for unit testing) We’ll focus on getting enough code working to write unit tests …
Printing This is easy – we’ll return a string consisting of <data left right> How can we write this for Tree<Integer>?
N-Ary Trees This takes the binary tree and replaces the two subtrees with a linked list of subtrees: class Tree<T> { public Link<Tree<T>> subtrees; public T data; public Tree(T data) { this.data = data; this.subtrees = null; }