Second Minimum Node In a Binary Tree
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.
Example 1:
Input:2/ \
25/ \
57
Output:5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input:2/ \
22
Output:-1
Explanation: The smallest value is 2, but there isn't any second smallest value.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/classSolution{public:int first=0;int second=-1;intfindSecondMinimumValue(TreeNode* root){if(root==NULL){return-1;}if(root->left==NULL&&root->right==NULL){return-1;}
first=root->val;//根结点一定是最小的corefunction(root->left);//对second分别在左右子树中两次更新得到最终的second值(这也是返回值为void的原因,要调用两次)corefunction(root->right);return second;}private://这个函数是为了找second的值
voidcorefunction(TreeNode*root){//更新一颗树的second值if(root==NULL){//这部分是对根节点,root为空,root不为空的话就开始比较root值和secondreturn;}//second == -1代表之前还未发现比根节点大的节点//如果second != -1且root.val < second 代表已经有比根节点大的值,但是目前的节点是更优解if(root->val>first){if(second==-1||second>root->val){
second=root->val;}}corefunction(root->left);corefunction(root->right);}//例如左子树调用时,此时是对左子树的根节点,左子树的左右子树调用的函数};