using
System;
using
System.Collections.Generic;
class
Node {
public
int
val;
public
List<Node> children;
public
Node()
{
val = 0;
children =
new
List<Node>();
}
}
public
class
MainClass {
static
Node NewNode(
int
val)
{
Node temp =
new
Node();
temp.val = val;
temp.children =
new
List<Node>();
return
temp;
}
static
void
PostOrder(Node root, List<
int
> nodes)
{
if
(root ==
null
)
return
;
foreach
(Node child
in
root.children)
{
PostOrder(child, nodes);
}
nodes.Add(root.val);
}
static
Dictionary<
int
,
int
> FindNextLarger(Node root)
{
List<
int
> nodes =
new
List<
int
>();
Dictionary<
int
,
int
> nextLarger
=
new
Dictionary<
int
,
int
>();
PostOrder(root, nodes);
Stack<
int
> stack =
new
Stack<
int
>();
for
(
int
i = nodes.Count - 1; i >= 0; i--) {
while
(stack.Count > 0
&& stack.Peek() <= nodes[i]) {
stack.Pop();
}
if
(stack.Count > 0) {
nextLarger[nodes[i]] = stack.Peek();
}
else
{
nextLarger[nodes[i]] = -1;
}
stack.Push(nodes[i]);
}
return
nextLarger;
}
public
static
void
Main()
{
Node root = NewNode(8);
root.children.Add(NewNode(3));
root.children.Add(NewNode(10));
root.children[0].children.Add(NewNode(1));
root.children[0].children.Add(NewNode(6));
root.children[0].children[1].children.Add(
NewNode(4));
root.children[0].children[1].children.Add(
NewNode(7));
root.children[1].children.Add(NewNode(14));
int
target = 4;
Dictionary<
int
,
int
> nextLarger
= FindNextLarger(root);
int
nextLargerValue;
if
(nextLarger.TryGetValue(target,
out
nextLargerValue)) {
Console.WriteLine(
"The next larger element for "
+ target
+
" is: "
+ nextLargerValue);
}
else
{
Console.WriteLine(
"The next larger element for "
+ target +
" is: -1"
);
}
}
}