Find Second Largest Node In BST
Question
Given the root to a binary search tree, find the second largest node in the tree.
Example
1 | Input: Root of below BST |
Solution
Brute force solution is more obvious, which means we just need traversal the whole tree and get the node we want, it costs O(n)
. But we want to improve it due to the property of BST. Actually, if we want to get the sorted result, we have to use inorder during the process, but normally, we use [left subtree], [visit], right subtree]
, that gives us ascending order. But for our problem we want to get the second largest node, so, we just need to change the order I mentioned before,[right subtree], [visit], left subtree]
Code
1 | // time:O(Height of Tree ~ logN) |