JAVA O(n) run-time, 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
    Z

    Recursion is not usually considered O(1). The recursion stack will use 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.