671. Second Minimum Node In a Binary Tree

406 篇文章 0 订阅
406 篇文章 0 订阅

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.
这里写图片描述
也就是找到一棵树的第二小的值,树的结构为每个节点,要么没有孩子,要么有两个孩子。孩子的值要大于等于该节点的值。

2,题目思路
个人的思路非常简单粗暴,就是直接DFS,对树进行遍历,push到向量中,然后再用sort(num.begin(), num.end())的方法进行排序(因为给定的树不是一般搜索二叉树,使得DFS的结果不是一个有序的数组),最后直接取第二小的即可。
参考了他人的思路,则是:
对与某个节点,如果它的节点和根节点的值相同,则继续搜索它的子树中的节点,直到找到和根节点的值不同的值为止,根据这棵树的具体特性,这个时候所得到的一定是第二小的值。

3,程序源码

class Solution {
public:
    int findSecondMinimumValue(TreeNode* root) {
        if (!root) return -1;
        int ans = minval(root, root->val);
        return ans;
    }
private:
    int minval(TreeNode* p, int first) {
        if (p == nullptr) return -1;//如果一直都在进行查找却没有找到不同的值,也就是找到了null的位置还没有,则直接返回-1.
        if (p->val != first) return p->val;
        int left = minval(p->left, first), right = minval(p->right, first);

        if (left == -1) return right;
        if (right == -1) return left;//如果左右都是-1,说明所有的节点的值都与根节点相同,这个时候就不存在第二小的值,根据题意直接返回-1
        return min(left, right);//左右子树都找到了一个最小值,这个时候返回最小的那个即可
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值