Skip to content

Commit 524a94f

Browse files
authored
Create Balanced-Binary-Tree.java and Updated README.md (#148)
* README file with Balanced-Binary-Tree problem * create Balanced-Binary-Tree.java
1 parent b804bc7 commit 524a94f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Java/Balanced-Binary-Tree.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public boolean isBalanced(TreeNode root) {
18+
19+
if(root==null){
20+
return true;
21+
}
22+
else{
23+
int left = height(root.left);
24+
int right = height(root.right);
25+
int diff = left - right;
26+
diff = diff > 0 ? diff : -diff; // absolute
27+
if(diff > 1){
28+
return false;
29+
}
30+
return isBalanced(root.left) && isBalanced(root.right);
31+
}
32+
}
33+
34+
private int height(TreeNode root){
35+
// calculate the height of a tree
36+
if(root == null){
37+
return 0;
38+
}
39+
else{
40+
int left = height(root.left);
41+
int right = height(root.right);
42+
int height = left > right ? left : right;
43+
return height + 1;
44+
}
45+
}
46+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
330330
| 1463 | [Cherry Pickup II](https://leetcode.com/problems/cherry-pickup-ii/) | [C++](./C++/Cherry-Pickup-II.cpp) | _O(n \* m)_ | _O(n \* m)_ | Hard | DFS | |
331331
| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | [python](./Python/maximum-depth-of-binary-tree.py) | _O(n)_ | _O(n)_ | Easy | DFS | |
332332
| 112 | [Path Sum](https://leetcode.com/problems/path-sum/) | [Java](./Java/path-sum.java) | _O(n)_ | _O(n)_ | Easy | DFS | |
333+
| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [Java](./Java/Balanced-Binary-Tree.java) | _O(n)_ | _O(n)_ | Easy | DFS | |
333334

334335
<br/>
335336
<div align="right">

0 commit comments

Comments
 (0)