-
Notifications
You must be signed in to change notification settings - Fork 1
/
leetcode110.java
39 lines (33 loc) · 963 Bytes
/
leetcode110.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null)
return true;
boolean balanceOfLeft=isBalanced(root.left);
if(balanceOfLeft==false)
return false;
boolean balanceOfRight=isBalanced(root.right);
if(balanceOfRight==false)
return false;
int depthOfLeft=depthOfTree(root.left);
int depthOfRight=depthOfTree(root.right);
if(Math.abs(depthOfLeft-depthOfRight)>1)
return false;
return true;
}
public int depthOfTree(TreeNode root){
if(root==null)
return 0;
int left=depthOfTree(root.left);
int right=depthOfTree(root.right);
return 1+(left>right?left:right);
}
}