Java DFS, no Set


  • 2
    M

    Hi, Everyone:
    I just want to share my solution here:

    class Solution {
        private Integer m1=null;
        private Integer m2=null;
        
        private void helper(TreeNode root){
            if(root==null)
                return;
            if( (m2==null && root.val>m1.intValue()) || (m2!=null && root.val>m1.intValue() && root.val<m2) )
                m2 = root.val;
            
            helper(root.left);
            helper(root.right);
        }
        
        public int findSecondMinimumValue(TreeNode root) {
            if(root==null)
                return -1;
            
            m1 = root.val;
            helper(root);
            if(m2==null)
                return -1;
            return m2.intValue();
        }
    }
    

  • 0
    F

    My dfs version

    class Solution {
        int min2 = Integer.MAX_VALUE;
        public int findSecondMinimumValue(TreeNode root) {
            dfs(root, root.val);
            return min2 == Integer.MAX_VALUE? -1 : min2;
        }
        public void dfs(TreeNode root, int min) {
            if (root == null) {
                return;
            }
            if (root.val != min &&  root.val - min < min2 - min) {
                min2 = root.val;
            }
            dfs(root.left, min);
            dfs(root.right, min);
        }
    }
    

Log in to reply
 

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