-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBalancedBinaryTree.java
60 lines (47 loc) · 1.55 KB
/
BalancedBinaryTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
/*
Runtime: 1 ms, faster than 99.18% of Java online submissions for Balanced Binary Tree.
Memory Usage: 43.8 MB, less than 78.67% of Java online submissions for Balanced Binary Tree.
*/
class Solution {
// For Storing Result
boolean flag = true;
// Main Function
public boolean isBalanced(TreeNode root) {
// For Calculating The Max Depth And Updating The Result Flag
maxDepth(root);
// Returning The Result Flag
return flag;
}
// Helper Function
public int maxDepth(TreeNode root){
// Base Condition For Recursion To Stop
if(root == null){
return 0;
}
// Calculating The Depth Of Left And Right Subtrees
int lengthLeft = maxDepth(root.left);
int lengthRight = maxDepth(root.right);
// Updating Condition
// If The Difference Of maxDepth Of Both Sides Becomes Greater Than 1, Then We Update The Flag To False
if(Math.abs(lengthLeft - lengthRight) > 1){
flag = false;
}
// Return Current Depth + 1
return Math.max(lengthLeft, lengthRight) + 1;
}
}