using
System;
public
class
Node {
public
int
key;
public
Node left, right;
public
Node(
int
key)
{
this
.key = key;
left = right =
null
;
}
}
public
class
Res {
public
int
r =
int
.MinValue;
}
public
class
BinaryTree {
public
Node root;
public
virtual
int
maxDiffUtil(Node t, Res res)
{
if
(t ==
null
) {
return
int
.MaxValue;
}
if
(t.left ==
null
&& t.right ==
null
) {
return
t.key;
}
int
val = Math.Min(maxDiffUtil(t.left, res),
maxDiffUtil(t.right, res));
res.r = Math.Max(res.r, t.key - val);
return
Math.Min(val, t.key);
}
public
virtual
int
maxDiff(Node root)
{
Res res =
new
Res();
maxDiffUtil(root, res);
return
res.r;
}
public
virtual
void
inorder(Node root)
{
if
(root !=
null
) {
inorder(root.left);
Console.Write(root.key +
""
);
inorder(root.right);
}
}
public
static
void
Main(
string
[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(8);
tree.root.left =
new
Node(3);
tree.root.left.left =
new
Node(1);
tree.root.left.right =
new
Node(6);
tree.root.left.right.left =
new
Node(4);
tree.root.left.right.right =
new
Node(7);
tree.root.right =
new
Node(10);
tree.root.right.right =
new
Node(14);
tree.root.right.right.left =
new
Node(13);
Console.WriteLine(tree.maxDiff(tree.root));
}
}