LeetCode //C - 671. Second Minimum Node In a Binary Tree

671. Second Minimum Node In a Binary Tree

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. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

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: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input: root = [2,2,2]
Output: -1
Explanation: The smallest value is 2, but there isn’t any second smallest value.

Constraints:
  • The number of nodes in the tree is in the range [1, 25].
  • 1 < = N o d e . v a l < = 2 31 − 1 1 <= Node.val <= 2^{31} - 1 1<=Node.val<=2311
  • root.val == min(root.left.val, root.right.val) for each internal node of the tree.

From: LeetCode
Link: 671. Second Minimum Node In a Binary Tree


Solution:

Ideas:
  • Constraint given: root->val == min(root->left->val, root->right->val)

  • So the root always contains the smallest value in the tree.

  • We do a DFS to search for the smallest value larger than root->val.

  • If a node has a value greater than root->val, it’s a candidate for second minimum.

  • Otherwise, keep searching its children.

Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int dfs(struct TreeNode* root, int minVal) {
    if (!root) return -1;
    
    if (root->val > minVal) {
        return root->val;
    }

    int left = dfs(root->left, minVal);
    int right = dfs(root->right, minVal);

    if (left == -1) return right;
    if (right == -1) return left;
    return left < right ? left : right;
}

int findSecondMinimumValue(struct TreeNode* root) {
    if (!root) return -1;
    return dfs(root, root->val);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值