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); } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 4276·2021-10-13 09:39
閱讀 482·2021-09-06 15:02
閱讀 3229·2019-08-30 15:53
閱讀 1040·2019-08-30 13:04
閱讀 2029·2019-08-30 11:27
閱讀 2010·2019-08-26 13:51
閱讀 2092·2019-08-26 11:33
閱讀 2902·2019-08-26 10:36