data-structures-and-algorithms-java

Trees

trees consist of:

Challenge

create a binary tree class , a Node class , and a BST that extends the binary tree class that has 2 methods :

  1. add
  2. contains

Approach & Efficiency

Complexity:
Time & Space complexity: O(n)

API

Challenge Summary

create a function that returns the maximum value in the tree
input: Tree
output: Integer

Whiteboard Process

whiteboard

Approach & Efficiency

complexity:
time complexity: O(n)
space complexity: O(n)

Solution

verification:

BST bst = new BST();  

bst.add(50);  
bst.add(30);  
bst.add(20);  
bst.add(40);  
bst.add(70);  
bst.add(60);  
bst.add(80);  

bst.getMaxValue(); // input  
// output: 80

Challenge Summary

create a function that takes a tree as an argument and return list of all values in the tree, in the order they were encountered (Breadth-first approach)

input: Tree
output: List

Whiteboard Process

whiteboard

Approach & Efficiency

complexity:
time complexity: O(n)
space complexity: O(n)

Solution

BST bst = new BST();

bst.add(50);
bst.add(30);
bst.add(20);
bst.add(40);
bst.add(70);
bst.add(60);
bst.add(80);

breadthFirst(bst); // input
// output: [50,30,70,20,40,60,80]

Challenge Summary

Determine whether or not the value of each node is divisible by 3, 5 or both. Create a new tree with the same structure as the original, but the values modified as follows:

input: k-ary tree
output: k-ary tree

Whiteboard Process

whiteboard

Approach & Efficiency

complexity:
time complexity: O(n)
space complexity: O(n)

Solution

KaryTree karyTree = new KaryTree(3);
Knode root = new Knode(10);
Knode node1 = new Knode(7);
Knode node2 = new Knode(15);
Knode node3 = new Knode(3);
Knode node4 = new Knode(8);
Knode node5 = new Knode(13);
Knode node6 = new Knode(20);

karyTree.setRoot(root);

root.getChildren().add(node1);
root.getChildren().add(node2);

node1.getChildren().add(node3);

node2.getChildren().add(node4);
node2.getChildren().add(node5);
node2.getChildren().add(node6);

fizzBuzz(karyTree);; // input
// output: tree with values changed to fizz, buzz, ,fizzbuzz, "int"