1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| public class Code_06_IsBalancedTree { public static class Node { public int value; public Node left; public Node right;
public Node(int data) { this.value = data; } } public static class ReturnData { public boolean isB; public int h;
public ReturnData(boolean isB, int h) { this.isB = isB; this.h = h; } }
public static boolean isB(Node head) { return process(head).isB; }
public static ReturnData process(Node head) { if (head == null) { return new ReturnData(true, 0); } ReturnData leftData = process(head.left); if (!leftData.isB) { return new ReturnData(false, 0); } ReturnData rightData = process(head.right); if (!rightData.isB) { return new ReturnData(false, 0); } if (Math.abs(leftData.h - rightData.h) > 1) { return new ReturnData(false, 0); } return new ReturnData(true, Math.max(leftData.h, rightData.h) + 1); } public static boolean isBalance(Node head) { boolean[] res = new boolean[1]; res[0] = true; getHeight(head, 1, res); return res[0]; }
public static int getHeight(Node head, int level, boolean[] res) { if (head == null) { return level; } int lH = getHeight(head.left, level + 1, res); if (!res[0]) { return level; } int rH = getHeight(head.right, level + 1, res); if (!res[0]) { return level; } if (Math.abs(lH - rH) > 1) { res[0] = false; } return Math.max(lH, rH); } }
|