judge if a tree is balanced
Sigiloso
/* I have written this code in java. I think it workd. I have used a small test case in the main() method. Please let me know if there are any flaws. */ import java.io.*; import java.lang.*; class Node { int value; Node left; Node right; Node (int value) { this.value = value; } } public class Tree { public int maxHeight(Node root) { if (root == null) return 0; else return (1 + Math.max(maxHeight(root.left), maxHeight(root.right))); } public int minHeight(Node root) { if (root == null) return 0; else return (1 + Math.min(maxHeight(root.left), maxHeight(root.right))); } public int isBalanced (Node root) { return ((Math.abs(this.maxHeight(root) - this.minHeight(root)))<=1?1:0); } public static void main(String argv[]) { Node root = new Node(0); Node child1 = new Node (1); Node child2 = new Node(2); Node child3 = new Node(3); Node child4 = new Node(4); root.left = child1; root.right = child2; child1.left = child3; child2.right = child4; Tree t = new Tree(); int n = t.isBalanced(root); System.out.println(+ n); } }