Second Minimal Node in a Binary Tree

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

BFS Solution

public class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        if (root == null) return -1;
        int res = Integer.MAX_VALUE, min = root.val; 
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node.val > min && node.val < res) res = node.val;
            if (node.left != null) q.offer(node.left);
            if (node.right != null) q.offer(node.right);
        }
        return res == Integer.MAX_VALUE ? -1 : res;
    }
}

Recursive Solution

public class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        int res = helper(root, Integer.MAX_VALUE, root.val);
        return res == Integer.MAX_VALUE ? -1 : res;
    }

    private int helper(TreeNode node, int res, int min) {
        if (node == null) return res;
        if (node.val > min && node.val < res) res = node.val;
        return Math.min(helper(node.left, res, min), helper(node.right, res, min));
    }
}

Analysis

From the problem description, we know that root.val is always the minimal value in entire tree
Hence we only need to find out the next minimal value except root
we use BFS and check if res changed to return the correct val
In the recursive solution, we apply the same idea and traversal the left and right subtree and return minimal one

results matching ""

    No results matching ""