671-Second Minimum Node In a Binary Tree
Description
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.
問題描述
給定一個非空的特殊的二叉樹, 它的每個節點有兩個或者0個子節點, 如果有兩個子節點, 那麼該節點的值為其兩個子節點中值較小的那個節點的值
你需要求出該二叉樹中第二小的值
如果不存在第二小的值, 返回-1
問題分析
令min1為最小值, ans為第二小的值
首先, 根節點是最小值, 問題是如何求出第二小的值
對於某個節點, 若它的值大於min1且小於第ans, 那麼可以將該節點的值作為後選址, 即ans = 該節點值
若它的值等於min1, 那麼在該節點的子樹中有可能找到第二小的值, 於是遍歷該節點的左右子樹
解法
class Solution {
//最小值
int min1;
//第二小的值, 也就是答案, 初始化
int ans = Integer.MAX_VALUE;
public void dfs(TreeNode root) {
//分兩種情況進行處理, 可以思考一下這兩種情況之外的情況為什麼不處理
if (root != null) {
if (min1 < root.val && root.val < ans) {
ans = root.val;
} else if (min1 == root.val) {
dfs(root.left);
dfs(root.right);
}
}
}
public int findSecondMinimumValue(TreeNode root) {
//注意這裡
min1 = root.val;
dfs(root);
return ans < Integer.MAX_VALUE ? ans : -1;
}
}
相關文章
- [LeetCode] 671. Second Minimum Node In a Binary TreeLeetCode
- 111-Minimum Depth of Binary Tree
- LeetCode のminimum-depth-of-binary-treeLeetCode
- Traversals of binary tree
- Leetcode Binary Tree PathsLeetCode
- CodeForces - 976A:Minimum Binary Number(水題)
- [LintCode] Binary Tree Level Order
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 543-Diameter of Binary Tree
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 226-Invert Binary Tree
- ABC 368D Minimum Steiner Tree
- 104. Maximum Depth of Binary Tree
- LeetCode 543. Diameter of Binary TreeLeetCode
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Leetcode 226. Invert Binary TreeLeetCode
- [leetcode]binary-tree-inorder-traversalLeetCode
- [leetcode]maximum-depth-of-binary-treeLeetCode
- 662. Maximum Width of Binary Tree
- 173. Binary Search Tree Iterator
- [LeetCode] 226. Invert Binary TreeLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- LeetCode之Univalued Binary Tree(Kotlin)LeetCodeKotlin
- LeetCode之Binary Tree Pruning(Kotlin)LeetCodeKotlin
- 662-Maximum Width of Binary Tree
- Binary-tree-level-order-traversal
- 104-Maximum Depth of Binary Tree
- 637-Average of Levels in Binary Tree
- 669-Trim a Binary Search Tree