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

来源:互联网 发布:tensorflow gpu 编辑:程序博客网 时间:2024/06/11 14:04

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);            }        }    }};
原创粉丝点击