您的位置:首页 > Web前端 > Node.js

LeetCode#671 Second Minimum Node In a Binary Tree (week13)

2017-12-05 00:37 447 查看

week13

题目

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.



原题地址:https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/

解析

题目要求找出给定二叉树的第二小元素(如果没有返回-1)

大致解题思路为:遍历该树,用两个整数记录目前找到的最小的元素A和第二小的元素B,找到比目前最小元素A更小的元素C则用A替代B成为第二小元素,C替代A成为最小元素;如果找到的元素C大于A但小于B,则直接用C代替B成为新的第二小元素。

代码

class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
int min = 1000000, secondMin = 1000001;
recursiveFind(root, min, secondMin);
if (secondMin == 1000000) {
return -1;
}
else {
return secondMin;
}
}
void recursiveFind(TreeNode* root, int &min, int &secondMin) {
if (root) {
if (root->val < min) {
secondMin = min;
min = root->val;
}
else if (root->val < secondMin && root->val!= min){
secondMin = root->val;
}
if (root->left) {
recursiveFind(root->left, min, secondMin);
}
if (root->right) {
recursiveFind(root->right, min, secondMin);
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ LeetCode