This algorithm does one run on the tree and returns the largest item at Item1
and second largest at Item2
.
The sort calls are O(1) because they are independent of the tree size.
So the total time complexity is O(N) and space complexity is O(log(N)) when the tree is balanced.
public static Tuple<int, int> SecondLargest(TreeNode<int> node)
{
int thisValue = node.Value;
if ((node.Left == null || node.Left.Right == null) && node.Right == null)
{
return new Tuple<int, int>(thisValue, -int.MaxValue);
}
else if (node.Left == null || node.Left.Right == null)
{
Tuple<int, int> right = SecondLargest(node.Right);
List<int> sortLargest = new List<int>(new int[] { right.Item1, right.Item2, thisValue });
sortLargest.Sort();
return new Tuple<int, int>(sortLargest[2], sortLargest[1]);
}
else if (node.Right == null)
{
Tuple<int, int> left = SecondLargest(node.Left.Right);
List<int> sortLargest = new List<int>(new int[] { left.Item1, left.Item2, thisValue });
sortLargest.Sort();
return new Tuple<int, int>(sortLargest[2], sortLargest[1]);
}
else
{
Tuple<int, int> left = SecondLargest(node.Left.Right);
Tuple<int, int> right = SecondLargest(node.Right);
List<int> sortLargest = new List<int>(new int[] { left.Item1, left.Item2, right.Item1, right.Item2, thisValue });
sortLargest.Sort();
return new Tuple<int, int>(sortLargest[4], sortLargest[3]);
}
}
The max element is the rightmost leaf in the BST.
No, with a "regular" BST having a key in each node it is "the rightmost node", but not a leaf: think a tree containing just the root and a leaf as a left child (the rightmost without doubt). (There are "leaf search trees" where all valid values are at the leaves (think string keys and the nodes just carrying prefixes allowing to decide left or right).) – Demodulate