Leetcode 671. Second Minimum Node In a Binary Tree
LeetCode Problem 671: Second Minimum Node In a Binary Tree
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. More formally, the property root.val = min(root.left.val, root.right.val)
always holds.
Find the second minimum value in this tree. If no such second minimum value exists, return -1.
Long.MAX_VALUE
(to handle larger secondary values).Here is the Java code to solve the problem:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public int findSecondMinimumValue(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) {
return -1;
}
return dfs(root, root.val);
}
private int dfs(TreeNode node, int minValue) {
if (node == null) {
return -1;
}
if (node.val > minValue) {
return node.val;
}
int left = dfs(node.left, minValue);
int right = dfs(node.right, minValue);
if (left > minValue && right > minValue) {
return Math.min(left, right);
}
return left > minValue ? left : right;
}
}
Time Complexity: The time complexity is (O(n)), where (n) is the number of nodes in the tree because we might visit each node once.
Space Complexity: The space complexity is (O(h)), where (h) is the height of the tree due to the recursive call stack. In the worst-case scenario (a completely unbalanced tree), this could be (O(n)). For a balanced tree, it would be (O(\log n)).
This approach ensures that we efficiently determine the second minimum value by traversing the tree effectively while adhering to the problem’s requirements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?