领扣LintCode算法问题答案-1094. 二叉树中次小的结点
发布日期:2021-06-30 17:09:50 浏览次数:3 分类:技术文章

本文共 1700 字,大约阅读时间需要 5 分钟。

领扣LintCode算法问题答案-1094. 二叉树中次小的结点

目录

1094. 二叉树中次小的结点

描述

给定一个非空的特别的结点包含非负值二叉树,其中树中的每一个节点包含正好两个或者零个子结点。如果这个结点有两个子结点,那么这个结点的值不大于它的两个子结点。

对于这样一个二叉树,你需要输出由整个树当中的结点值构成的集合中的次小值。

如果不存在这样的一个次小值,输出-1作为替代。

样例 1:

输入:     2   / \  2   5     / \    5   7输出: 5解释: 最小的值是2,次小值是5.

样例 2:

输入:     2   / \  2   2输出: -1解释: 最小值是2,但是没有次小值.

题解

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {
/** * @param root: the root * @return: the second minimum value in the set made of all the nodes' value in the whole tree */ public int findSecondMinimumValue(TreeNode root) {
// Write your code here if (root == null) {
return -1; } if (root.left != null && root.right != null) {
if (root.left.val > root.val && root.right.val > root.val) {
return Math.min(root.left.val, root.right.val); } if (root.left.val > root.val || root.right.val > root.val) {
return Math.max(root.left.val, root.right.val); } int mLv = findSecondMinimumValue(root.left); int mRv = findSecondMinimumValue(root.right); if (mLv != -1 && mRv != -1) {
if (mLv > root.val || mRv > root.val) {
return Math.min(mLv, mRv); } } } return -1; }}

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。

欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

转载地址:https://le-yi.blog.csdn.net/article/details/108809458 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1099. 不下降数组
下一篇:【精】LintCode领扣算法问题答案:1086. 重复字符串匹配

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月12日 00时19分23秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章