605

.pdf

School

University of Texas *

*We aren’t endorsed by this school

Course

CS201

Subject

Computer Science

Date

Apr 30, 2024

Type

pdf

Pages

4

Uploaded by msway on coursehero.com

1.) // Initializes the tree with a specified size and sets the root to -1 FUNCTION makeTree(size) tree = new TreeNode[size] root = -1 // Creates a new TreeNode with the given item and initializes children to -1 FUNCTION createNode(item) node = new TreeNode() node.item = item node.leftChild = -1 node.rightChild = -1 node.isThread = false RETURN node // Sets the left child of a given parent node to a new node with the specified item FUNCTION setLeft(parentIndex, item) leftIndex = 2 * parentIndex + 1 tree[leftIndex] = createNode(item) tree[parentIndex].leftChild = leftIndex // Sets the right child of a given parent node to a new node with the specified item // In addition, if isThread is true, it marks the rightChild as a thread rather than a normal child node FUNCTION setRight(parentIndex, item, isThread) rightIndex = 2 * parentIndex + 2 IF NOT isThread tree[rightIndex] = createNode(item) tree[parentIndex].rightChild = rightIndex ELSE tree[parentIndex].rightChild = rightIndex tree[parentIndex].isThread = true // Creates the root of the tree with the specified item FUNCTION makeTreeWithRoot(item) IF root == -1 tree[0] = createNode(item) root = 0 2.) FUNCTION inOrderTraversal(rootIndex) IF rootIndex == -1
RETURN // Find the leftmost node first currentNodeIndex = findLeftmost(rootIndex) WHILE currentNodeIndex != -1 visit(tree[currentNodeIndex]) // If the right child is a thread, follow it to the next node in in-order sequence IF tree[currentNodeIndex].isThread currentNodeIndex = tree[currentNodeIndex].rightChild ELSE // If not a thread, find the leftmost node of the right child to continue traversal currentNodeIndex = findLeftmost(tree[currentNodeIndex].rightChild) // Loop continues until all the nodes are visited // Finds the leftmost node starting from a given node index FUNCTION findLeftmost(nodeIndex) WHILE nodeIndex != -1 AND tree[nodeIndex].leftChild != -1 nodeIndex = tree[nodeIndex].leftChild RETURN nodeIndex FUNCTION visit(node) //Whatever you want to do with that node 3.) // A = array with data values FUNCTION sortUsingCount(A) n = LENGTH(A) DECLARE Count[n] DECLARE Output[n] // Create a count array for the length FOR i FROM 0 TO n - 1 Count[i] = 0 // THIS IS IMPORTANT: Count the number of items smaller than each A[i], we need to check if it’s smaller FOR i FROM 0 TO n - 1 FOR j FROM 0 TO n - 1
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help