Skip to content

Instantly share code, notes, and snippets.

@xeinebiu
Last active May 7, 2020 08:56
Show Gist options
  • Save xeinebiu/0f0016d441839bcd72513c1c147e438f to your computer and use it in GitHub Desktop.
Save xeinebiu/0f0016d441839bcd72513c1c147e438f to your computer and use it in GitHub Desktop.
// Given the root to a binary search tree, find the second largest node in the tree.
// https://dotnetfiddle.net/ZLdVSy
class Program
{
public class Node
{
public int Value { get; private set; }
public Node Left { get; private set; }
public Node Right { get; private set; }
public Node(int value, Node left, Node right)
{
this.Left = left;
this.Right = right;
this.Value = value;
}
}
public static void Main(string[] args)
{
//set up
Node two = new Node(2, null, null);
Node four = new Node(4, null, null);
Node six = new Node(6, null, null);
Node ten = new Node(10, null, null);
Node three = new Node(3, two, four);
Node eight = new Node(8, six, ten);
Node root = new Node(5, three, eight);
Console.WriteLine(FindSecondMax(root));
}
private static int? FindSecondMax(Node root)
{
const int maxIndex = 1;
const int secondMaxIndex = 0;
var top2Max = new int?[2] { null, null };
var queue = new Queue<Node>();
queue.Enqueue(root);
do
{
var currNode = queue.Dequeue();
var currMax = top2Max[maxIndex];
var currSecondMax = top2Max[secondMaxIndex];
if (currMax == null || currNode.Value > currMax)
{
top2Max[secondMaxIndex] = currMax;
top2Max[maxIndex] = currNode.Value;
}
else if (currSecondMax == null || currNode.Value > currSecondMax)
top2Max[secondMaxIndex] = currNode.Value;
if (currNode.Left != null)
queue.Enqueue(currNode.Left);
if (currNode.Right != null)
queue.Enqueue(currNode.Right);
} while (queue.Count > 0);
return top2Max[secondMaxIndex] ?? top2Max[maxIndex];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment