aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Hunteman <michael@huntm.net>2022-10-01 19:05:51 -0500
committerMichael Hunteman <michael@huntm.net>2022-10-01 19:05:51 -0500
commit3cf6cd56951542e9096d0ca58fc332053c3f74c2 (patch)
tree8a3d58acccb451ee797f1dd2b800dea30a009522
parent27cd471ef172362cfdf8621c0c9a1c4edd35863e (diff)
Add Max Depth of Tree
-rw-r--r--MaxDepthOfTree.java22
-rw-r--r--node/ListNode.java8
-rw-r--r--node/TreeNode.classbin0 -> 466 bytes
-rw-r--r--node/TreeNode.java19
4 files changed, 47 insertions, 2 deletions
diff --git a/MaxDepthOfTree.java b/MaxDepthOfTree.java
new file mode 100644
index 0000000..b1597cf
--- /dev/null
+++ b/MaxDepthOfTree.java
@@ -0,0 +1,22 @@
+import java.lang.*;
+import java.util.*;
+import node.*;
+
+class MaxDepthOfTree {
+ public static int maxDepth(TreeNode root) {
+ if (root.left == null || root.right == null)
+ return 1;
+ int l = maxDepth(root.left) + 1;
+ int r = maxDepth(root.right) + 1;
+ return l > r ? l : r;
+ }
+
+ public static void main(String[] args) {
+ TreeNode leftLeaf = new TreeNode(9);
+ TreeNode middleLeaf = new TreeNode(15);
+ TreeNode rightLeaf = new TreeNode(7);
+ TreeNode parent = new TreeNode(20, middleLeaf, rightLeaf);
+ TreeNode root = new TreeNode(3, leftLeaf, parent);
+ System.out.println(maxDepth(root));
+ }
+}
diff --git a/node/ListNode.java b/node/ListNode.java
index 6b345ec..33e1803 100644
--- a/node/ListNode.java
+++ b/node/ListNode.java
@@ -4,6 +4,10 @@ public class ListNode {
public int val;
public ListNode next;
public ListNode() {}
- public ListNode(int val) { this.val = val;}
- public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
+ public ListNode(int val) {
+ this.val = val;
+ }
+ public ListNode(int val, ListNode next) {
+ this.val = val; this.next = next;
+ }
}
diff --git a/node/TreeNode.class b/node/TreeNode.class
new file mode 100644
index 0000000..634ad75
--- /dev/null
+++ b/node/TreeNode.class
Binary files differ
diff --git a/node/TreeNode.java b/node/TreeNode.java
new file mode 100644
index 0000000..b820151
--- /dev/null
+++ b/node/TreeNode.java
@@ -0,0 +1,19 @@
+package node;
+
+import java.lang.*;
+import java.util.*;
+
+public class TreeNode {
+ public int val;
+ public TreeNode left;
+ public TreeNode right;
+ public TreeNode() {}
+ public TreeNode(int val) {
+ this.val = val;
+ }
+ public TreeNode(int val, TreeNode left, TreeNode right) {
+ this.val = val;
+ this.left = left;
+ this.right = right;
+ }
+}