Java easy recursive solution


  • 0
    J

    Use two member variables to keep current min and secondMin. Traverse the tree to update min and secondMin when you encounter a node value less than min or secondMin.

    class Solution {
        public int min = Integer.MAX_VALUE;
        public int secondMin = Integer.MAX_VALUE;
        
        public int findSecondMinimumValue(TreeNode root) {
            traverse(root);
            if (secondMin==Integer.MAX_VALUE) 
                return -1; 
            else 
                return secondMin;         
        }
        
        public void traverse(TreeNode root) {
            if (root==null) return;
            if (root.val<min) {
                secondMin = min; 
                min = root.val;
            }
            else if (root.val>min && root.val<secondMin) {
                secondMin=root.val; 
            }
            
            traverse(root.left);
            traverse(root.right);
        }
    }
    

    Complexity O(n). Space O(1).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.