MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / dfs

Method dfs

java/0110-balanced-binary-tree.java:5–22  ·  view source on GitHub ↗
(TreeNode root)

Source from the content-addressed store, hash-verified

3class BalancedBinaryTree {
4
5 private static Pair<Boolean, Integer> dfs(TreeNode root) {
6 if (root == null) {
7 return new Pair<Boolean, Integer>(true, 0);
8 }
9
10 var left = dfs(root.left);
11 var right = dfs(root.right);
12
13 var balanced =
14 left.getKey() &&
15 right.getKey() &&
16 (Math.abs(left.getValue() - right.getValue()) <= 1);
17
18 return new Pair<Boolean, Integer>(
19 balanced,
20 1 + Math.max(left.getValue(), right.getValue())
21 );
22 }
23
24 public static boolean isBalanced(TreeNode root) {
25 return dfs(root).getKey();

Callers 1

isBalancedMethod · 0.95

Calls 1

getKeyMethod · 0.45

Tested by

no test coverage detected