671. Second Minimum Node In a Binary Tree

本文探讨了如何在特殊二叉树中寻找第二小的节点值。通过递归遍历,利用二叉树节点值的特点,高效地找到答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值