Skip to content

Commit 7962072

Browse files
committed
Added Depth First Search pattern
1 parent b65c624 commit 7962072

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

GrokkingDepthFirstSearch.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.cunningdj.grokJava;
2+
3+
import java.util.Stack;
4+
5+
class GrokkingDepthFirstSearch {
6+
public static void main(String[] args) {
7+
Tester tester = new Tester();
8+
String testTitle="";
9+
10+
// TREE_HEIGHT
11+
testTitle = "TREE_HEIGHT";
12+
TreeNode root = buildTestTree();
13+
tester.intEquals(5, treeHeight(root), testTitle);
14+
root.right.left.left.right.right = new TreeNode(88);
15+
tester.intEquals(6, treeHeight(root), testTitle);
16+
}
17+
18+
public static TreeNode buildTestTree() {
19+
// Builds a sample tree for testing. Returns the tree root
20+
// LEVEL 1
21+
TreeNode root = new TreeNode(1);
22+
23+
// LEVEL 2
24+
root.left = new TreeNode(2);
25+
root.right = new TreeNode(3);
26+
27+
// LEVEL 3
28+
root.left.left = new TreeNode(4);
29+
root.right.left = new TreeNode(6);
30+
root.right.right = new TreeNode(7);
31+
32+
// LEVEL 4
33+
root.left.left.right = new TreeNode(9);
34+
root.right.left.left = new TreeNode(11);
35+
36+
// LEVEL 5
37+
root.right.left.left.right = new TreeNode(20);
38+
39+
return root;
40+
}
41+
42+
public static int treeHeight(TreeNode root) {
43+
if (root == null) {
44+
return 0;
45+
}
46+
47+
int maxHeight = 0;
48+
Stack<NodeHeightPair> st = new Stack<>();
49+
st.push(new NodeHeightPair(root, 1));
50+
NodeHeightPair nhp;
51+
while (st.size() > 0) {
52+
nhp = st.pop();
53+
if (nhp.node.left == null && nhp.node.right == null) {
54+
maxHeight = Math.max(maxHeight, nhp.height);
55+
} else {
56+
if (nhp.node.right != null) {
57+
st.push(new NodeHeightPair(nhp.node.right, nhp.height + 1));
58+
}
59+
if (nhp.node.left != null) {
60+
st.push(new NodeHeightPair(nhp.node.left, nhp.height + 1));
61+
}
62+
}
63+
}
64+
return maxHeight;
65+
}
66+
67+
private static class NodeHeightPair {
68+
TreeNode node;
69+
Integer height;
70+
public NodeHeightPair(TreeNode node, Integer height) {
71+
this.node = node;
72+
this.height = height;
73+
}
74+
}
75+
}

TreeNode.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.cunningdj.grokJava;
2+
3+
class TreeNode {
4+
public int value;
5+
public TreeNode left;
6+
public TreeNode right;
7+
8+
// CONSTRUCTOR(S)
9+
public TreeNode(int value) {
10+
this.value = value;
11+
this.left = null;
12+
this.right = null;
13+
}
14+
15+
public TreeNode(int value, TreeNode left, TreeNode right) {
16+
this.value = value;
17+
this.left = left;
18+
this.right = right;
19+
}
20+
}

0 commit comments

Comments
 (0)