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

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);
            }
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值