Skip to content

Commit 0eff576

Browse files
solves balanced binary tree
1 parent 05ae5df commit 0eff576

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/MaximumDepthOfBinaryTree.java) |
3838
| 107 | [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/BinaryTreeLevelOrderTraversalII.java) |
3939
| 108 | [Convert Sorted Array To Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ConvertSortedArrayToBinarySearchTree.java) |
40-
| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree) | Easy |
40+
| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)]() |
4141
| 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree) | Easy |
4242
| 112 | [Path Sum](https://leetcode.com/problems/path-sum) | Easy |
4343
| 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle) | Easy |

src/BalancedBinaryTree.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public class BalancedBinaryTree {
2+
private static class TreeNode {
3+
int val;
4+
TreeNode left;
5+
TreeNode right;
6+
}
7+
8+
public static boolean isBalanced(TreeNode root) {
9+
return height(root) != -1;
10+
}
11+
12+
private static int height(TreeNode root) {
13+
if (root == null) {
14+
return 0;
15+
}
16+
17+
int leftDepth = height(root.left);
18+
int rightDepth = height(root.right);
19+
if (leftDepth == -1 || rightDepth == -1 || Math.abs(rightDepth - leftDepth) > 1) {
20+
return -1;
21+
}
22+
23+
return 1 + Math.max(leftDepth, rightDepth);
24+
}
25+
}

0 commit comments

Comments
 (0)