import java.util.Stack;
public class Node {
Node left;
Node right;
int maxLeft;
int maxRight;
int value;
public static void main(String args[]){
Node node1 = new Node(null, null, 1);
Node node7 = new Node(null, null, 7);
Node node12 = new Node(null, null, 12);
Node node8 = new Node(null, node1, 8);
Node node4 = new Node(null, node8, 4);
Node node5 = new Node(node4, node7, 5);
Node node10 = new Node(node12, node5,10);
Stack stack = new Stack();
//findPath(node10, 22, stack);
System.out.println(findMaxLen(node10));
}
public Node(Node left, Node right, int value){
this.left = left;
this.right = right;
this.value = value;
}
public static void findPath(Node node, int sum, Stack stack){
stack.push(node.value);
sum -= node.value;
if(sum == 0){
printPath(stack);
}
if (node.left != null){
findPath(node.left, sum, stack);
}
if(node.right != null){
findPath(node.right, sum, stack);
}
sum += node.value;
stack.pop();
return;
}
public static void printPath(Stack stack){
Object objs[] = stack.toArray();
System.out.println();
for(Object obj : objs){
System.out.print(obj+"->");
}
}
public static int findMaxLen(Node node){
int maxLength = 0;
int maxLeftLength = 0;
int maxLeftHeight = 0;
int maxRightHeight = 0;
if(node.left != null){
maxLeftHeight = findMaxHeight(node.left);
maxLeftLength = findMaxLen(node.left);
}
int maxRightLength = 0;
if(node.right != null){
maxRightHeight = findMaxHeight(node.right);
maxRightLength = findMaxLen(node.right);
}
if(maxLeftLength > maxRightLength){
maxLength = maxLeftLength;
} else {
maxLength = maxRightLength;
}
if(maxLength < maxLeftHeight + maxRightHeight){
maxLength = maxLeftHeight + maxRightHeight;
}
return maxLength;
}
public static int findMaxHeight(Node node){
int maxHeigth = 0;
int maxLeftHeight = 0;
if(node.left != null){
maxLeftHeight = findMaxHeight(node.left);
}
int maxRightHeight = 0;
if(node.right != null){
maxRightHeight = findMaxHeight(node.right);
}
if(maxLeftHeight > maxRightHeight){
maxHeigth = maxLeftHeight + 1;
} else {
maxHeigth = maxRightHeight + 1;
}
return maxHeigth;
}
}