Second Minimum Node In a Binary Tree
Problem
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. More formally, the property root.val = min(root.left.val, root.right.val)
always holds.
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.
Constraints
- The number of nodes in the tree is in the range
[1, 25]
. 1 <= Node.val <= 231 - 1
root.val == min(root.left.val, root.right.val)
for each internal node of the tree.
Solution
The problem Second Minimum Node In a Binary Tree
can be solved using a recursion. Since the root node’s value is guaranteed to be the smallest, smallest value from either the left or right subnodes that does not equal to the root node’s value would become the second smallest value.
Implementation
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
unsigned int helper(TreeNode *root)
{
if (root->left == NULL)
return UINT_MAX;
unsigned int left = root->val == root->left->val ? helper(root->left) : root->left->val;
unsigned int right = root->val == root->right->val ? helper(root->right) : root->right->val;
return min(left, right);
}
int findSecondMinimumValue(TreeNode *root)
{
unsigned int ret = helper(root);
return ret == UINT_MAX ? -1 : ret;
}
};