leetcode 671. Second Minimum Node In a Binary Tree

来源:互联网 发布:移动4g卡首选网络类型 编辑:程序博客网 时间:2024/06/04 22:08

1.题目

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.

翻译: 一棵非空的二叉树,每一个节点的值是它的两个子节点中较小的那个值。求该二叉树中第二小的数。如果不存在则输出-1
Example 1:
Input:

    2   / \  2   5     / \    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:
Input:

    2   / \  2   2

Output: -1
Explanation: The smallest value is 2, but there isn’t any second smallest value.

2.分析

首先,根节点的值是整棵树的最小值。我们的目标是找到不等于根结点值的剩下所有节点的最小值。

可以深度遍历树,把值放入set中,取第二个值。
也可以在遍历的过程中比较节点值,保存第二小的值。

3.代码

int minVal(TreeNode* node, int val) {    if (node->val != val)        return node->val;    else if (node->val == val && node->left)        return min(minVal(node->left, val), minVal(node->right, val));    else        return INT_MAX;}int findSecondMinimumValue(TreeNode* root) {    if (root == NULL || root->left == NULL)        return -1;    int val = root->val;    int ans = minVal(root,val);    return ans == INT_MAX ? -1 : ans;}

或者存放在set中

int findSecondMinimumValue2(TreeNode* root) {    set<int> vals;    stack<TreeNode*> nodes;    nodes.push(root);    while (!nodes.empty()) {//BFS        TreeNode* node = nodes.top();        nodes.pop();        vals.insert(node->val);        if (node->left)            nodes.push(node->left);        if (node->right)            nodes.push(node->right);    }    set<int>::iterator it = vals.begin();    if (vals.size() > 1)//取第二个元素        return *(++it);    else        return -1;}