Lab 3
Lab 3
Lab 3
Variable Declaration
✤ var cse482 // scoped to immediate function body)
✤ let cse482 // scoped to immediate block. Recommended)
Functions
function cse482 () {
var cse482 = "cse482"
console.log("Hi from function " + cse482)
}
cse482()
randomFunction()
printInputString("This is a string input!")
perimeter () {
return 2 * Math.PI * this.radius
}
area () {
return Math.PI * Math.pow(this.radius, 2);
}
console.log(newCircle.area())
console.log(newCircle.perimeter())
area:
function () {
return Math.PI * Math.pow(this.radius, 2)
}
}
console.log(newCircle.area())
console.log(newCircle.perimeter())
Arrays
✤ Can be sparse ([100, 0, , , , 2])
✤ Can be polymorphic ([2, true, "CSE482", 2.009])
✤ Some of the many methods: push, pop, shift, unshift, sort, reverse, length. Look them up!
No Pointers in JavaScript
When you pass a variable (string, object, function, number, etc) to a function or an object, it is
either pass-by-value or pass-by-reference. Primitive data types (string, number, etc) are passed by
value, and complex data types (object, function) are passed by reference.
class Node {
constructor(val){
this.val = val
this.left = null
this.right = null
}
}
class BST {
constructor(){
this.root = new Node(null)
}
insert (val) {
this.insert_val(val, this.root)
console.log(val + " has been inserted")
}
}
}
print_level_order () {
if (this.root.val == null)
return "Empty tree"
while (queue.length) {
current = queue.shift()
visited.push(current.val)
if (current.left != null)
queue.push(current.left)
if (current.right != null)
queue.push(current.right)
}
return visited
}
search (val) {
print_pre_order () {
}
print_post_order () {
}}
Create a file named bst.js and copy the above source code into the file. Create another file named
test_bst.html in the same directory and insert the following code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="bst.js"></script>
</head>
<body>
<script type="text/javascript">
console.log(tree.print_level_order())
</script>
</body>
</html>
Your task will be to complete the functions search, print_pre_order and print_post_order. The
functions are described below:
1. search: This function will take in a value and search for its presence in the Binary Search
Tree. If present, the function returns true, and false otherwise.
2. print_pre_order and print_post_order will print your Binary Search Tree in pre-order and
post-order patterns respectively. Look them up if needed.