Second Minimum Node In a Binary Tree (671)
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two
or zero
sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Approach 1 : DFS
The KEY point of this problem is to observe that this tree's root node's val is always the smallest value.
We then use an Array with
index 0
being the value at the root.node andindex 1
being the location which will store the second smallest value. **Additionnally, I used anInteger
object for the array in lieu of a primitive (int
) array to avert an error in the advent that the only other element in the tree isInteger.MAX_VALUE
. (primitive long array type would have also worked as it can compare numbers that are greater than 31bit like the aforementioned).Upon this fact, we traverse the tree's node recursively and while the node that we're currently visiting does not equal what was at the initial root node(res[0]), we update res[1] to take the smallest node's value that we visit ------- Since the array is passed by reference, we always have have access to res[0] which is subsequently used as an anchor to compare each nodes and make sure they do not equal to the initial root.val.
**(primitive long array type would have also worked to compare Integer.MAX_VALUE
has it can store more than 31bits.
Time: O(N) Space: O(1)
Approach 2 : BFS
I used a level order traversal and implemented the same logic above. (see 1.3)
Time: O(N) Space: O(N)
Last updated
Was this helpful?