Problem
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.Solution
class Solution { public int findSecondMinimumValue(TreeNode root) { if(root == null || root.left == null) return -1; int leftRes, rightRes; if (root.left.val == root.val) { leftRes = findSecondMinimumValue(root.left); } else { leftRes = root.left.val; } if (root.right.val == root.val) { rightRes = findSecondMinimumValue(root.right); } else { rightRes = root.right.val; } if (leftRes == -1 && rightRes == -1) return -1; else if (leftRes == -1) return rightRes; else if (rightRes == -1) return leftRes; else return Math.min(leftRes, rightRes); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72365.html
摘要:解题思路用递归实现很简单,对于每个根节点,最大深度就等于左子树的最大深度和右子树的最大深度的较大值。解题思路本题的注意点在于如果某个根节点有一边的子树为空,那么它的深度就等于另一边不为空的子树的深度,其他的逻辑与上一题相同。 Maximum Depth of Binary TreeGiven a binary tree, find its maximum depth. The maxi...
摘要:递归法复杂度时间空间递归栈空间思路简单的递归。该递归的实质是深度优先搜索。这里我们还有改进的余地,就是用迭代加深的有限深度优先搜索。 Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the l...
摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...
摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...
摘要:做了几道二分法的题目练手,发现这道题已经淡忘了,记录一下。这道题目的要点在于找的区间。边界条件需要注意若或数组为空,返回空当前进到超出末位,或超过,返回空每次创建完根节点之后,要将加,才能进行递归。 Construct Binary Tree from Inorder and Preorder Traversal Problem Given preorder and inorder t...
阅读 4123·2021-10-13 09:39
阅读 443·2021-09-06 15:02
阅读 3199·2019-08-30 15:53
阅读 997·2019-08-30 13:04
阅读 1968·2019-08-30 11:27
阅读 1953·2019-08-26 13:51
阅读 2042·2019-08-26 11:33
阅读 2871·2019-08-26 10:36