Skip to content

Commit fc698b9

Browse files
committed
Refactored Chapter 4
1 parent 4a6e4c0 commit fc698b9

16 files changed

+505
-162
lines changed

src/chapter3/ThreePoint3.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public void push (int data){
1313
if (lastStack != null && lastStack.size() < capacity)
1414
lastStack.push(data);
1515
else{
16-
Stack<Integer> anotherStack = new Stack<>();
16+
Stack<Integer> anotherStack = new Stack<>(); // crucial step. Stacks aren't magically created 4 u.
1717
anotherStack.push(data);
1818
stacks.add(anotherStack);
1919
}

src/chapter4/Chapter4.java

Lines changed: 123 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,134 @@
11
package chapter4;
22

3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
36
public class Chapter4 {
47
public static void main(String [] args){
5-
//4.1 - No need to test. I just compared my code to the book
6-
//4.2 - Would have to implemented a Directed Graph, and proper Nodes, to test.
8+
test_DFS();
9+
test_BFS();
10+
test_PrintPreOrder();
11+
test_PrintInOrder();
12+
test_PrintPostOrder();
13+
test_PrintLevelOrder();
14+
test_FourPoint1();
15+
test_FourPoint2();
16+
test_FourPoint3();
17+
test_FourPoint4();
18+
test_FourPoint5();
19+
test_FourPoint6();
20+
test_FourPoint7();
21+
test_FourPoint8();
22+
test_FourPoint9();
23+
}
24+
25+
public static void test_DFS(){
26+
GraphNode graphNode = GraphFunctions.createGraph();
27+
System.out.println("\n*** Test DFS");
28+
GraphFunctions.DFS(graphNode, 6); // searches for value 6
29+
}
30+
31+
public static void test_BFS(){
32+
GraphNode graphNode = GraphFunctions.createGraph();
33+
System.out.println("\n*** Test BFS");
34+
GraphFunctions.DFS(graphNode, 6); // searches for value 6
35+
}
736

8-
/*** 4.3 ***/
9-
System.out.println("*** Test 4.3: BST from sorted array");
37+
public static void test_PrintPreOrder(){
38+
TreeNode tree = TreeFunctions.createBST();
39+
System.out.println("\n*** Test print (pre-order)");
40+
TreeFunctions.printPreOrder(tree);
41+
}
42+
43+
public static void test_PrintInOrder(){
44+
TreeNode tree = TreeFunctions.createBST();
45+
System.out.println("\n\n*** Test print (in-order)");
46+
TreeFunctions.printInOrder(tree);
47+
}
48+
49+
public static void test_PrintPostOrder(){
50+
TreeNode tree = TreeFunctions.createBST();
51+
System.out.println("\n\n*** Test print (post-order)");
52+
TreeFunctions.printPostOrder(tree);
53+
}
54+
55+
public static void test_PrintLevelOrder(){
56+
TreeNode tree = TreeFunctions.createBST();
57+
System.out.println("\n\n*** Test print (level-order)");
58+
TreeFunctions.printLevelOrder(tree);
59+
}
60+
61+
public static void test_FourPoint1(){
62+
TreeNode tree = TreeFunctions.createBST();
63+
System.out.println("\n\n*** Test 4.1: (Balanced Trees)");
64+
System.out.println("(Solution 1) Is balanced? " + FourPoint1.isBalanced(tree));
65+
System.out.println("(Solution 2) Is balanced? " + FourPoint1.isBalanced_2(tree));
66+
}
67+
68+
/* Testing is not thorough, I just do a simple test */
69+
public static void test_FourPoint2(){
70+
System.out.println("\n*** Test 4.2: Route exists");
71+
GraphNode node1 = new GraphNode(1);
72+
GraphNode node2 = new GraphNode(2);
73+
node1.addNeighbor(node2);
74+
System.out.println("Route exists? (should be true): " + FourPoint2.routeExists(node1, node2));
75+
}
76+
77+
public static void test_FourPoint3(){
78+
System.out.println("\n*** Test 4.3: BST from sorted array");
1079
int [] sortedArray = {1, 2, 3, 4, 5, 6, 7};
1180
TreeNode BST = FourPoint3.createBST(sortedArray);
1281
System.out.print("In-Order print of tree: ");
13-
FourPoint3.inOrderPrint(BST);
14-
15-
//4.4 - My solution is same as book code. Too lazy to test.
16-
//4.5 - My solution is same as book code. Too lazy to test.
17-
//4.6 - My solution is same as book code. Too lazy to test.
18-
//4.7 - My solution is same as book code. Too lazy to test.
19-
//4.8 - My solution is same as book code. Too lazy to test.
20-
21-
/*** 4.9 ***/
22-
System.out.print("\n\n*** Test 4.9: Tree paths summing to value");
23-
TreeNode n = new TreeNode(4);
24-
n.left = new TreeNode(1);
25-
n.left.left = new TreeNode(0);
26-
n.right = new TreeNode(-1);
27-
n.right.left = new TreeNode(2);
28-
n.right.right = new TreeNode(4);
29-
30-
FourPoint9.findSum(n, 5);
31-
82+
TreeFunctions.printInOrder(BST);
83+
}
84+
85+
public static void test_FourPoint4(){
86+
TreeNode tree = TreeFunctions.createBST();
87+
System.out.println("\n\n*** Test 4.4: create lists by level");
88+
ArrayList<LinkedList<TreeNode>> lists = FourPoint4.createLinkedLists(tree);
89+
for (LinkedList<TreeNode> list : lists){
90+
System.out.print("\nNew level ");
91+
for (TreeNode node : list){
92+
System.out.print(node);
93+
}
94+
}
95+
}
96+
97+
public static void test_FourPoint5(){
98+
TreeNode tree1 = TreeFunctions.createTree();
99+
TreeNode tree2 = TreeFunctions.createBST();
100+
System.out.println("\n\n*** Test 4.5: is BST?");
101+
System.out.println("Should be false: " + FourPoint5.isBST(tree1));
102+
System.out.println("Should be true: " + FourPoint5.isBST(tree2));
103+
}
104+
105+
public static void test_FourPoint6(){
106+
TreeNode tree = TreeFunctions.createBST();
107+
System.out.println("\n*** Test 4.6: Find inOrderSucc");
108+
System.out.println("Should be 6: " + FourPoint6.inOrderSucc(tree));
109+
System.out.println("Should be 5: " + FourPoint6.inOrderSucc(tree.left));
110+
System.out.println("Should be null: " + FourPoint6.inOrderSucc(tree.right.right));
111+
}
112+
113+
public static void test_FourPoint7(){
114+
TreeNode tree = TreeFunctions.createBST();
115+
System.out.println("\n*** Test 4.7: Common ancestor");
116+
System.out.println("Common ancestor should be 5: " + FourPoint7.commonAncestor(tree, tree.left, tree.right.right));
117+
System.out.println("Common ancestor should be 8: " + FourPoint7.commonAncestor(tree, tree.right, tree.right.left));
118+
}
119+
120+
public static void test_FourPoint8(){
121+
TreeNode tree1 = TreeFunctions.createTree();
122+
TreeNode tree2 = TreeFunctions.createBST();
123+
System.out.println("\n*** Test 4.8: subTree");
124+
System.out.println("Should be false: " + FourPoint8.containsTree(tree1, tree2));
125+
}
126+
127+
public static void test_FourPoint9(){
128+
System.out.print("\n*** Test 4.9: Tree paths summing to value");
129+
TreeNode tree = TreeFunctions.createBST();
130+
FourPoint9.findSum(tree, 6);
32131
System.out.print("\n\nSolution version 2");
33-
FourPoint9.findSum2(n, 5);
34-
35-
132+
FourPoint9.findSum2(tree, 6);
36133
}
37134
}

src/chapter4/FourPoint1.java

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
package chapter4;
22

33
public class FourPoint1 {
4-
/* Solution 1 (crappy solution) - Did this perfectly on my own 1st time through book.
5-
* But it's O(n^2) because it's O(n) to check the heights, for each of the n nodes, so n*n = n^2.
6-
* We have been recalculating the same heights over and over again. See other solution (below) to avoid this
4+
/* Solution 1 (Naive, slow runtime solution)
5+
* It's O(n^2) because it's O(n) to check the height from a node, which we got to do for each of the n nodes, so n*n = n^2.
6+
* We have been recalculating the same heights over and over again. See other solution (below) to avoid this.
77
*/
8-
public static boolean balanced(TreeNode root){
8+
public static boolean isBalanced(TreeNode root){
99
if (root == null)
1010
return true;
1111

1212
int leftTreeHeight = height(root.left);
1313
int rightTreeHeight = height(root.right);
14-
if (Math.abs(leftTreeHeight - rightTreeHeight) > 1)
14+
15+
if (Math.abs(leftTreeHeight - rightTreeHeight) > 1) // this just checks if it's balanced at THIS node, not all nodes.
1516
return false;
16-
return balanced(root.left) && balanced(root.right);
17+
return isBalanced(root.left) && isBalanced(root.right);
1718
}
1819

1920
private static int height(TreeNode root){
@@ -23,28 +24,30 @@ private static int height(TreeNode root){
2324
return 1 + Math.max(height(root.left), height(root.right));
2425
}
2526

26-
/* Solution 2 - Did this perfectly on my own 2nd time through book. I prefer this solution.
27-
* Book O(n) time, O(h) space solution. This is achieved by checking heights while we're checking if tree is balanced
28-
*/
29-
public static boolean balanced2(TreeNode root){
27+
/***************************************************************************************************************************/
28+
/* Solution 2 - Book O(n) time, O(h) space solution. Achieved by checking heights while we're checking if tree is balanced */
29+
/***************************************************************************************************************************/
30+
public static boolean isBalanced_2(TreeNode root){
3031
if (checkHeight(root) == -1)
3132
return false;
3233
else
3334
return true;
3435
}
3536

37+
/* Returns -1 if unbalanced, otherwise returns height of tree from given node */
3638
private static int checkHeight(TreeNode root){
3739
if (root == null)
38-
return 0; //height of 0. Crucial to return 0, and not -1.
40+
return 0; // height of 0. Crucial to return 0, and not -1.
3941

4042
int leftHeight = checkHeight(root.left);
4143
int rightHeight = checkHeight(root.right);
44+
4245
if (leftHeight == -1)
43-
return -1; //left tree is unbalanced
46+
return -1; // left tree is unbalanced
4447
if (rightHeight == -1)
45-
return -1; //right tree is unbalanced
48+
return -1; // right tree is unbalanced
4649
if (Math.abs(leftHeight - rightHeight) > 1)
47-
return -1; //imbalance between the 2 subtrees
50+
return -1; // imbalance between the 2 subtrees
4851

4952
return 1 + Math.max(leftHeight, rightHeight);
5053
}

src/chapter4/FourPoint2.java

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
11
package chapter4;
2-
//import java.util.LinkedList;
3-
/***********************************************************************************************/
4-
/******** THIS IS PSEUDOCODE (which I commented out so no compiler errors***********************/
5-
/***********************************************************************************************/
6-
//Notice we use LinkedList instead of ArrayList cuz we're often removing 1st element
72

3+
import java.util.Queue;
4+
import java.util.LinkedList;
5+
6+
/* Finding if a route exists is simply BFS or DFS to see if we reach the desired node */
87
public class FourPoint2 {
9-
/* Will employ standard BFS */
10-
/* For "Graph", we have "getNodes()". For "Node", we have "getAdjacent()" and "visit() */
8+
/* We do BFS from start node to see if we arrive at end node */
9+
public static boolean routeExists(GraphNode start, GraphNode end){
10+
if (start == end)
11+
return true;
1112

12-
/*
13-
public static boolean routeExists(Graph g, Node start, Node end){
14-
LinkedList<Node> queue = new LinkedList<Node>(); //couldn't create a "Queue" since Queue is an INTERFACE in Java. "LinkedList" implements this interface
13+
Queue<GraphNode> queue = new LinkedList<>();
1514
start.visit();
16-
while (!queue.isEmpty()){
17-
Node offQueue = queue.removeFirst();
18-
for (Node n : offQueue.getAdjacent()){
19-
if (!n.visited){
20-
if (n == end)
21-
return true;
22-
n.visit();
23-
queue.add(n);
15+
queue.add(start);
16+
17+
while ( ! queue.isEmpty()){
18+
GraphNode curr = queue.remove();
19+
if (curr == end)
20+
return true;
21+
for (GraphNode neighbor : curr.getNeighbors()){
22+
if ( ! neighbor.visited){
23+
neighbor.visit();
24+
queue.add(neighbor);
2425
}
2526
}
2627
}
2728
return false;
2829
}
29-
*/
3030
}

src/chapter4/FourPoint3.java

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,22 @@
11
package chapter4;
22

3-
/* Main Trick: Binary Search
4-
* I did this all on my own (1st time through book). Worked perfectly. (I had to look up binary search though, as a quick refresher */
3+
/* Main Trick: Binary Search */
54
public class FourPoint3 {
65
public static TreeNode createBST(int [] sortedArray){
76
if (sortedArray == null)
87
return null;
98
return createBST_Helper(sortedArray, 0, sortedArray.length - 1);
109
}
1110

12-
/* Simple Binary Search: I always seem to code this without errors */
11+
/* Simple Binary Search */
1312
private static TreeNode createBST_Helper(int [] sortedArray, int startIndex, int endIndex){
1413
if (startIndex > endIndex)
1514
return null;
15+
1616
int mid = (startIndex + endIndex) / 2;
1717
TreeNode root = new TreeNode(sortedArray[mid]);
18-
root.left = createBST_Helper(sortedArray, startIndex, mid - 1);
18+
root.left = createBST_Helper(sortedArray, startIndex, mid - 1);
1919
root.right = createBST_Helper(sortedArray, mid + 1, endIndex);
2020
return root;
2121
}
22-
23-
/* This is here to check my result */
24-
public static void inOrderPrint(TreeNode root){
25-
if (root == null)
26-
return;
27-
inOrderPrint(root.left);
28-
System.out.print(root.data + " ");
29-
inOrderPrint(root.right);
30-
}
31-
3222
}

src/chapter4/FourPoint4.java

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,39 @@
11
package chapter4;
2+
23
import java.util.ArrayList;
34
import java.util.LinkedList;
45

5-
/* Good problem */
66
/* Tricky Skills:
77
* 1) Knowing I should return an "ArrayList<LinkedList<Node>>".
88
* 2) Knowing that, to alter the "ArrayList<LinkedList<Node>>", I should be passing it as a parameter so it can be altered.
9-
* 3) Know to also pass the "level" down the tree
10-
* 4) Making a DEEP COPY whenever we add Nodes to the list.
9+
* 3) Know to also pass the "level" down the tree.
10+
* 4) Remembering to create new LinkedLists in our ArrayList when necessary.
11+
* 5) Making a DEEP COPY whenever we add Nodes to the list.
1112
*/
1213
public class FourPoint4 {
13-
ArrayList<LinkedList<TreeNode>> createLinkedLists(TreeNode root){ //it was tricky knowing what data structure to return.
14+
public static ArrayList<LinkedList<TreeNode>> createLinkedLists(TreeNode root){
1415
ArrayList<LinkedList<TreeNode>> lists = new ArrayList<LinkedList<TreeNode>>();
1516
createLinkedListsHelper(lists, root, 0);
1617
return lists;
1718
}
1819

19-
void createLinkedListsHelper(ArrayList<LinkedList<TreeNode>> lists, TreeNode root, int level){
20-
if (root == null)
20+
/* Recursive Solution (loosely based off DFS) */
21+
public static void createLinkedListsHelper(ArrayList<LinkedList<TreeNode>> lists, TreeNode node, int currLevel){
22+
if (node == null)
2123
return;
22-
/* May need a new list for a new level */
23-
if (lists.size() == level) //levels are visited in order, so this should work.
24+
25+
/* Tricky. May need a new list for a new level */
26+
if (lists.size() == currLevel) // levels are visited in order, so this should work.
2427
lists.add(new LinkedList<TreeNode>());
2528

2629
/* Add this Node */
27-
LinkedList<TreeNode> list = lists.get(level); //get the appropriate list to add the node to.
28-
list.add(new TreeNode(root.data)); //DEEP COPY (This is the only step I forgot the 2nd time I coded this)
30+
LinkedList<TreeNode> list = lists.get(currLevel);//get the appropriate list to add the node to.
31+
list.add(new TreeNode(node.data)); // DEEP COPY - don't forget!
2932

3033
/* Recursively add this nodes subtrees */
31-
createLinkedListsHelper(lists, root.left, level + 1);
32-
createLinkedListsHelper(lists, root.right, level + 1);
33-
34+
createLinkedListsHelper(lists, node.left, currLevel + 1);
35+
createLinkedListsHelper(lists, node.right, currLevel + 1);
3436
}
3537
}
3638

37-
/* Solution 2: Iterative solution in book. I don't like it */
39+
/* Solution 2: Iterative solution based of BFS in book. Makes sense but I like the above solution better */

0 commit comments

Comments
 (0)