-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIsBalanced_Solution.java
More file actions
38 lines (30 loc) · 942 Bytes
/
IsBalanced_Solution.java
File metadata and controls
38 lines (30 loc) · 942 Bytes
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
package com.company;
import org.junit.Test;
public class IsBalanced_Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) return true;
int leftDepth = treeDepth(root.left);
int rightDepth = treeDepth(root.right);
if (Math.abs(leftDepth - rightDepth) > 1)
return false;
return IsBalanced_Solution(root.left) &&
IsBalanced_Solution(root.right);
}
public int treeDepth(TreeNode mTreeNode) {
if (mTreeNode == null) return 0;
int left = treeDepth(mTreeNode.left) + 1;
int right = treeDepth(mTreeNode.right) + 1;
return Math.max(left, right);
}
@Test
public void test() {
}
}