Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 5, 2017 01:27
Show Gist options
  • Save cixuuz/6ea8ea65b2c4e97b11b2dca2e07f04c3 to your computer and use it in GitHub Desktop.
Save cixuuz/6ea8ea65b2c4e97b11b2dca2e07f04c3 to your computer and use it in GitHub Desktop.
[110 Balanced Binary Tree] #leetcode
/**
* 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;
}
return Math.abs(depth(root.left) - depth(root.right)) <= 1 &&
isBalanced(root.left) && isBalanced(root.right);
}
private int depth(TreeNode node) {
if (node == null) {
return 0;
}
return Math.max(depth(node.left), depth(node.right)) + 1;
}
}
public class Solution1 {
public boolean isBalanced(TreeNode root) {
return depth(root) != -1;
}
private int depth(TreeNode node) {
if (node == null) {
return 0;
}
int left = depth(node.left);
int right = depth(node.right);
if (left == -1 || right == -1) {
return -1;
}
if ( Math.abs(left - right) <= 1 ) {
return Math.max(left, right) + 1;
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment