LeetCode 671 Second Minimum Node In a Binary Tree?

given a tree which each val of the nodes are positive. output the second minimum node in a binary tree…
pay attention: the second minimum should be the value larger than smallest if we can’t find somrthing like this then we return -1;

in order to get the second minimum value we need to get the smallest. and we can us a PQ to store all the nodes and then pop up the first.
but we need to store all the node val in the PQ which will take a lot of space.

so we can maintain two variables as the smallest two tree, but we need to make sure than these two maintains different.

I believe this problem can be solved in recursion too, and the equation will be:
the following code should work but somehow can’t work, and based on the output, I suspect it still output the duplicate min.
but the logic seems perfect.

class Solution {
    private int min = Integer.MAX_VALUE;
    private int secMin = Integer.MAX_VALUE;
    public int findSecondMinimumValue(TreeNode root) {
        find(root);
        if (secMin == Integer.MAX_VALUE) {
            return -1;
        }
        return secMin;
    }
    
    private void find(TreeNode root) {
        if (root == null) return;
        if (root.val < min) {
            min = root.val;
            secMin = min;
        } else if (root.val != min && root.val < secMin) { 
            secMin = root.val;
        }
        find(root.left);
        find(root.right);
    }
}
posted @ 2020-11-16 22:29  EvanMeetTheWorld  阅读(23)  评论(0)    收藏  举报