Created
July 3, 2014 05:55
-
-
Save chouclee/5a7bdbed1ab1c8b3d150 to your computer and use it in GitHub Desktop.
[CC150][4.1/5th e.d.]Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one
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
public class BST<Key extends Comparable<Key>> { | |
private Node root; | |
private boolean isBalanced; | |
private class Node { | |
private Key key; | |
private Node left, right; | |
public Node(Key key) | |
{ this.key = key; } | |
} | |
public BST(Key[] keys) { | |
for (Key key : keys) | |
put(key); | |
} | |
public void put(Key key) { | |
root = put(root, key); | |
} | |
private Node put(Node x, Key key) { | |
if (x == null) return new Node(key); | |
int cmp = key.compareTo(x.key); | |
if (cmp < 0) x.left = put(x.left, key); | |
else if (cmp > 0) x.right = put(x.right, key); | |
return x; | |
} | |
public boolean isBalanced() { | |
if (root == null) return true; | |
isBalanced = true; | |
int lv = countLv(root); | |
System.out.println(lv); | |
if (isBalanced) return true; | |
return false; | |
} | |
private int countLv(Node x) { | |
if (x == null) | |
return 0; | |
int countNextLeft = countLv(x.left); | |
int countNextRight = countLv(x.right); | |
if (Math.abs(countNextLeft - countNextRight) >= 2) | |
isBalanced = false; | |
return Math.max(countNextLeft, countNextRight) + 1; | |
} | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
Integer data[] = {7,4,9,2,5,8,10,1,3,6,11}; | |
/* 7 | |
* / \ | |
* / \ | |
* / \ | |
* 4 9 | |
* / \ / \ | |
* 2 5 8 10 | |
* / \ \ \ | |
* 1 3 6 11 | |
* / | |
* 0 | |
*/ | |
BST<Integer> test = new BST<Integer>(data); | |
if (test.isBalanced()) | |
System.out.println("Balanced"); | |
else System.out.println("Not Balanced"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment