671. Second Minimum Node In a Binary Tree

来源:互联网 发布:nginx tomcat 配置ssl 编辑:程序博客网 时间:2024/05/21 17:15

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.

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. 分析

  • 每个节点的值是左右子叶的一个最小值, 所以整棵树的根节点一定是最小的
  • 如果一个节点的左子树空, 也就是说这个节点只能由右子树产生, 反之一样
  • 如果一个节点和父节点的值一样, 继续分左右搜索, 不一样表示已经找到了候选值。因为到了这一层表示父节点所在的那一层的数和根节点一样, 所以这个节点需要和兄弟节点比较选一个小的就可以了

3. 代码

/** * 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 getSecond(TreeNode* root, int min){        if (!root) return -1;        /*        *这里比较重要, 当发现有不等于根节点的数出现, 就可以返回传给上层函数(父节点的getSecond中的left 或者 right).        */        if (root->val != min) return root->val;        int left = getSecond(root->left, min);        int right = getSecond(root->right, min);        if (left == -1) return right;        if (right == -1) return left;        return left>right?right:left;    }    int findSecondMinimumValue(TreeNode* root) {        if (!root) return -1;        int min = root->val;        int ans = getSecond(root, min);        return ans;    }};
原创粉丝点击