-
class TreeNode {
-
public int val;
-
public TreeNode left;
-
public TreeNode right;
-
public TreeNode(int val) {
-
this.val = val;
- }
-
public TreeNode() {
- }
- }
-
public class TestTree {
-
public static int n;
-
ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>();
-
ArrayList<Integer> list = new ArrayList<Integer>();
-
public static void main(String[] args) {
-
int[] array = new int[] { 7, 4, 5, 6, 0, 0, 0, 0, 8, 0, 9, 0, 10, 0, 0 };
-
TestTree t = new TestTree();
-
TreeNode root = t.CreateTreeBinary(new TreeNode(), array);
-
System.out.println(t.IsBalanced_Solution(root));
- }
-
public TreeNode CreateTreeBinary(TreeNode treeNode, int[] array) {
-
if (array[n] == 0) {
-
n++;
-
return null;
-
} else {
-
treeNode.val = array[n++];
-
treeNode.left = CreateTreeBinary(new TreeNode(0), array);
-
treeNode.right = CreateTreeBinary(new TreeNode(0), array);
-
return treeNode;
- }
- }
-
private boolean isBalanced = true;
-
public boolean IsBalanced_Solution(TreeNode root) {
-
getDepth(root);
-
return isBalanced;
- }
-
public int getDepth(TreeNode root) {
-
if (root == null)
-
return 0;
-
int left = getDepth(root.left);
-
int right = getDepth(root.right);
-
System.out.print(" root: " + root.val);
-
System.out.print(" Math.abs(left - right): " + Math.abs(left - right));
-
System.out.print(" left: " + left);
-
System.out.println(" right: " + right);
-
if (Math.abs(left - right) > 1) {
-
isBalanced = false;
- }
-
return right > left ? right + 1 : left + 1;
- }
- }