Easy JAVA solution O(1) Space


  • -1
    A
    class Solution {
        int small = Integer.MAX_VALUE;
        int sec_small = Integer.MAX_VALUE;
        public int findSecondMinimumValue(TreeNode root) {
            if(root==null) return -1;
            dfs(root);
            return sec_small!=Integer.MAX_VALUE? sec_small: -1;
        }
        
        public void dfs(TreeNode root){
            if(root==null) return;
            if(root.val<small){
                sec_small = small;
                small = root.val;
            }else if(root.val <sec_small && root.val!=small) sec_small = root.val;
            dfs(root.left);
            dfs(root.right);
        }
    }
    

  • 0

    Not O(1) space but O(height of tree) space.


Log in to reply
 

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