










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!











David Galles
Department of Computer Science
University of San Francisco
07-0:
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-2:
(Length of the path to the deepest leaf) + 1
Height = 5
Height = 6
07-3:
int height(Node tree) {
if (tree == null)
return 0; return 1 + MAX(height(tree.left()),
height(tree.right()));
07-5:
int numNodes(Node tree) {
if (tree == null)
return 0; return 1 + numNodes(tree.left(),
tree.right());
07-6:
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
Tree
Tree
Tree
Write
find, numLeaves, shallowestleaf
07-8:
int numLeaves(Node tree) {
if (tree == null)
return 0; if ((tree.left() == null) &&
(tree.right() == null)) return 1; return numLeaves(tree.left()) +
numLeaves(tree.right());
07-9:
Do operation on root of the tree Traverse left subtree Traverse right subtree INORDER Traversal
Traverse left subtree Do operation on root of the tree Traverse right subtree POSTORDER Traversal
Traverse left subtree Traverse right subtree Do operation on root of the tree
07-11:
Printing out trees (Showing the shape of the tree in theprintout)
First print the root at current indent level
Print the left subtree with larger indentation Print the right subtree with larger indentation
07-12:
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-14:
Calculating the Value of an expression tree
07-15:
Calculating the Value of an expression tree
Base case:
Return value stored at leaf Recursive case:
Calculate value of left subtree Calculate value of right subtree Calculate expression value