using
System;
using
System.Collections.Generic;
public
class
GFG {
public
class
Node {
public
int
data;
public
Node left, right;
public
Node(
int
d) {
data = d;
left = right =
null
;
}
};
public
class
pair {
public
int
first, second;
public
pair(
int
first,
int
second) {
this
.first = first;
this
.second = second;
}
}
static
int
ans = 1;
static
pair[] maxApPath(Node root) {
pair[] l = {
new
pair(
int
.MaxValue, 0),
new
pair(
int
.MaxValue, 0) };
pair[] r = {
new
pair(
int
.MaxValue, 0),
new
pair(
int
.MaxValue, 0) };
int
leftDiff =
int
.MaxValue;
int
rightDiff =
int
.MaxValue;
if
(root.left !=
null
) {
l = maxApPath(root.left);
leftDiff = (root.data) - (root.left.data);
}
if
(root.right !=
null
) {
r = maxApPath(root.right);
rightDiff = (root.data) - (root.right.data);
}
int
maxLen1 = 0;
int
maxLen2 = 0;
if
(leftDiff == l[0].first || l[0].first ==
int
.MaxValue) {
maxLen1 = l[0].second;
}
if
(leftDiff == l[1].first || l[1].first ==
int
.MaxValue) {
maxLen1 = Math.Max(maxLen1, l[1].second);
}
if
(rightDiff == r[0].first || r[0].first ==
int
.MaxValue) {
maxLen2 = r[0].second;
}
if
(rightDiff == r[1].first || r[1].first ==
int
.MaxValue) {
maxLen2 = Math.Max(maxLen2, r[1].second);
}
if
(leftDiff == (-1 * rightDiff)) {
ans = Math.Max(ans, maxLen1 + maxLen2 + 1);
}
else
{
ans = Math.Max(Math.Max(ans, maxLen1 + 1), maxLen2 + 1);
}
return
new
pair[] {
new
pair(leftDiff, maxLen1 + 1),
new
pair(rightDiff, maxLen2 + 1) };
}
public
static
void
Main(String[] args) {
Node root =
new
Node(1);
root.left =
new
Node(8);
root.right =
new
Node(6);
root.left.left =
new
Node(6);
root.left.right =
new
Node(10);
root.right.left =
new
Node(3);
root.right.right =
new
Node(9);
root.left.left.right =
new
Node(4);
root.left.right.right =
new
Node(12);
root.right.right.right =
new
Node(12);
root.left.left.right.right =
new
Node(2);
root.right.right.right.left =
new
Node(15);
root.right.right.right.right =
new
Node(11);
maxApPath(root);
Console.Write(ans);
}
}