Last active
August 29, 2015 14:15
-
-
Save dmnugent80/66eec8b16a2b435c4809 to your computer and use it in GitHub Desktop.
Is BST Balanced
This file contains hidden or 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) { | |
if (root == null) return true; | |
if (root.left == null && root.right == null) return true; | |
int left = 0; | |
int right = 0; | |
if (root.left != null) | |
left = getHeight(root.left); | |
if (root.right != null) | |
right = getHeight(root.right); | |
if (Math.abs(left - right) > 1){ | |
return false; | |
} | |
else{ | |
return isBalanced(root.left) && isBalanced(root.right); | |
} | |
} | |
public int getHeight(TreeNode node){ | |
if (node == null) return 0; | |
return Math.max(getHeight(node.left), getHeight(node.right)) + 1; | |
} | |
} | |
//Alternate: | |
/** | |
* 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) { | |
if (root == null) return true; | |
if (root.left == null && root.right == null) return true; | |
int left = 0; | |
int right = 0; | |
if (root.left != null) | |
left = getHeight(root.left, 1); | |
if (root.right != null) | |
right = getHeight(root.right, 1); | |
if (Math.abs(left - right) > 1){ | |
return false; | |
} | |
else{ | |
return isBalanced(root.left) && isBalanced(root.right); | |
} | |
} | |
public int getHeight(TreeNode node, int level){ | |
if (node.left == null && node.right == null){ | |
return level; | |
} | |
int left = 0; | |
int right = 0; | |
if (node.left != null) | |
left = getHeight(node.left, level + 1); | |
if (node.right != null) | |
right = getHeight(node.right, level + 1); | |
return Math.max(left, right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment