



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Notes; Professor: Galles; Class: Data Struct & Algorithms; Subject: Computer Science; University: University of San Francisco (CA); Term: Summer III 2009;
Typology: Study notes
1 / 5
This page cannot be seen from the preview
Don't miss anything!
07-0: Binary Tree Definition
class Node { Node() { } Node(Comparable elem) { element_ = element; } Node(Object element, Node left, Node right) { element_ = element; left_ = left; right_ = right; } /* Access methods on next slide */ private Node left_; private Node right_; private Comparable element_; }
07-1: Binary Tree Access Methods
Node left() { void setLeft(Node left) { return left_; left_ = left; } }
Node right() { void setRight(Node right) { return right_; right_ = right; } }
Comparable element() { return element_; }
void setElement(Comparable element) { element_ = element; }
07-2: Tree Operations – Height
Height = 5 Height = 6 07-3: Tree Operations – Height
int height(Node tree) { if (tree == null) return 0; return 1 + MAX(height(tree.left()), height(tree.right())); }
07-4: Tree Operations – NumNodes
Number of Nodes = 8 Number of Nodes = 6 07-5: Tree Operations – NumNodes
int numNodes(Node tree) { if (tree == null) return 0; return 1 + numNodes(tree.left(), tree.right());
07-6: Writing Tree Functions
1
2
3
4
5
1
2 3 4 5
6
7 8
9 10 11 12
13
14 15
8
3
2 4
5
Tree1 (^) Tree
Tree
07-10: PREORDER Traversal
Printing out trees (Showing the shape of the tree in the printout)
07-11: PREORDER Traversal Printing out trees (Showing the shape of the tree in the printout)
07-12: Printing Binary Trees
void print(Node tree, int indent) { if (tree != null) { for(int i=0; i<indent; i++) { System.out.print("\t"); System.out.println(tree.element().toString()); print(tree.left(), indent + 1); print(tree.right(), indent + 1); }
07-13: INORDER Traversal Printing all elements in a Binary Search Tree in order
07-14: POSTORDER Traversal Calculating the Value of an expression tree
07-15: POSTORDER Traversal
Calculating the Value of an expression tree
07-16: Expression Tree Value
int value(Node tree) { if (tree.left() == null && tree.right() == null) return ((Integer) tree.element()).intValue(); int left = value(tree.left()); int right = value (tree.right()); char op = ((Character) tree.element()).charValue(); switch (op) { case ’+’: return left + right; case ’*’: return left * right; ... } }