671. Second Minimum Node In a Binary Tree

来源:互联网 发布:高功能自闭症 知乎 编辑:程序博客网 时间:2024/06/05 07:58

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly twoor 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.

Example 1:

Input:     2   / \  2   5     / \    5   7Output: 5Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input:     2   / \  2   2Output: -1Explanation: 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) {} * }; */class Solution {public:    int findSecondMinimumValue(TreeNode* root) {        if(!root){            return -1;        }        int second_min = INT_MAX;        queue<TreeNode*> q;        q.push(root);        while(!q.empty()){            int size = q.size();            for(int i = 0; i < size; ++i){                TreeNode* temp = q.front();                q.pop();                              if(temp->val > root->val){                    if(temp->val < second_min){                        second_min = temp->val;                    }                }                                if(temp->left) q.push(temp->left);                if(temp->right) q.push(temp->right);            }        }        if(second_min == INT_MAX){            return -1;        }else{            return second_min;        }    }    };


class Solution {public:    int findSecondMinimumValue(TreeNode* root) {        if (!root) return -1;        int ans = minval(root, root->val);        return ans;    }private:    int minval(TreeNode* p, int first) {        if (p == nullptr) return -1;        if (p->val != first) return p->val;        int left = minval(p->left, first), right = minval(p->right, first);        // if all nodes of a subtree = root->val,         // there is no second minimum value, return -1        if (left == -1) return right;        if (right == -1) return left;        return min(left, right);    }};


原创粉丝点击