This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public boolean isBalanced(TreeNode root) { | |
int res = getBalance(root); | |
return res == -1? false: true; | |
} | |
private int getBalance(TreeNode node) { | |
if (node == null) | |
return 0; | |
int left = getBalance(node.left); | |
int right = getBalance(node.right); | |
if (left == -1 || right == -1) | |
return -1; | |
int diff = abs(left - right); | |
return diff > 1? -1: max(left, right) + 1; | |
} | |
private int abs(int x) { | |
return x < 0? -x: x; | |
} | |
private int max(int a, int b) { | |
return a >= b? a: b; | |
} | |
} |
No comments:
Post a Comment