2011Winter2009_Assignment2_solution - Department of...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Department of Computer Science and Engineering York University, Winter 2009 CSE 2011: Assignment 2 Due Date - Friday, May 11, by Noon ! Question 1 Binary Tree Traversal [15 points] The recursive implementations of Preorder and Inorder Traversal on a binary tree are provided below. void recursivePreorder(Node t) { if (t != null) { processNode(t); recursivePreorder(t.getLeft()); recursivePreorder(t.getRight()); } } void recursiveInorder(Node t) { if (t != null) { recursiveInorder(t.getLeft()); processNode(t); recursiveInorder(t.getRight()); } } Write a corresponding non-recursive version of both above methods. (Hint: you are allowed to use an additional data structure, e.g. a stack or a queue.) Solution: void nonRecursivePreorder (Node t) { Stack s = new Stack(); s.push(t); while (!s.isEmpty()) { t = s.pop(); processNode(t); Node right = t.rightChild(); if (right != null) { s.push(right); } Node left = t.leftChild(); if (left != null) { s.push(left); } } }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 v o i d nonRecursiveInorder (Node t) { Stack s = new Stack(); s.push(t); while (!s.isEmpty()) { if (t != null) { t = t.leftChild(); if (t != null ) { s.push(t); } } else { t = (Node) s.pop(); processNode(t); t = t.rightChild(); if (t != null) { s.push(t); } } } } Question 2 Binary Search Tree [15 points] In a binary search tree, in addition to the standard operations, we want to support an operation called findLargest (K), that takes integer K as an argument and returns the K-th largest key in the tree. In
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/30/2010 for the course CSE 2011 taught by Professor Nguyen during the Spring '10 term at Maple Springs Baptist Bible College.

Page1 / 5

2011Winter2009_Assignment2_solution - Department of...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online