Docsity

Tree Operations in Data Structures and Algorithms CS245 - Prof. David J. Galles, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Tree Operations in Data Structures and Algorithms CS245 - Prof. David J. Galles and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms

CS245-2009S-07Tree Operations

David Galles

Department of Computer Science

University of San Francisco

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-2:

Tree Operations โ€“ Height Returns the height of the tree

(Length of the path to the deepest leaf) + 1

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-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

Tree

Tree

Tree

Write

find, numLeaves, shallowestleaf

07-8:

Tree Operations โ€“ NumLeaves

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:

Tree Traversals PREORDER Traversal

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:

PREORDER Traversal

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:

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-14:

POSTORDER Traversal

Calculating the Value of an expression tree

07-15:

POSTORDER Traversal

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