LeetCode 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.
struct Node
{
int value;
Node* left;
Node* right;
};
int secondMinimum(Node* root)
{
int ret = INT_MAX;
stack<Node*> s;
s.push(root);
Node* curr = NULL;
while(!s.empty())
{
curr = s.top();
s.pop();
if(curr->left)
{
if(curr->left->value != root->value)
{
if(curr->left->value < ret) ret = curr->left->value;
}
else
{
s.push(curr->left);
}
if(curr->right->value != root->value)
{
if(curr->right->value < ret) ret = curr->right->value;
}
else
{
s.push(curr->right);
}
}
}
return ret;
}
int main()
{
Node a , b , c;
a.value = 2;
a.left = &b;
a.right = &c;
b.value = 2;
b.left = NULL;
b.right = NULL;
c.value = 3;
c.left = NULL;
c.right = NULL;
int ret = secondMinimum(&a);
cout<<ret<<endl;
}