Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

104. Maximum Depth of Binary Tree #44

Merged
merged 2 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.xtenzq.tree;

import com.xtenzq.tree.utils.TreeNode;

public class BinaryTree {

/**
* Computes the maximum depth of a binary tree.
*
* @param root the root node of the binary tree
* @return the maximum depth of the binary tree
* @implNote The time complexity of this method is {@code O(n)}, where n is the number of nodes in the binary tree.
* This is because the method visits each node exactly once.
* <p>
* The space complexity of this method is {@code O(h)}, where {@code h} is the height of the binary tree.
* This is due to the recursion stack. In the worst case, the height of the tree can be {@code n} (in case of a completely skewed tree).
* Therefore, the space complexity can be considered {@code O(h)} in the worst case and {@code O(log h)} in the best case (for a balanced tree).
* @see <a href="https://leetcode.com/problems/maximum-depth-of-binary-tree/">104. Maximum Depth of Binary Tree</a>
*/
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}

int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.xtenzq.tree;

import org.junit.jupiter.api.Test;

import static com.xtenzq.tree.BinaryTree.maxDepth;
import static com.xtenzq.tree.utils.TreeNode.buildTree;
import static org.junit.jupiter.api.Assertions.assertEquals;

class BinaryTreeTest {

@Test
void maxDepth_case1() {
assertEquals(3, maxDepth(buildTree(3, 9, 20, null, null, 15, 7)));
}

@Test
void maxDepth_case2() {
assertEquals(2, maxDepth(buildTree(1, null, 2)));
}
}
Loading