Java[DFS], Super Easy to Understand


  • 0
    Z
        public int findSecondMinimumValue(TreeNode root) {
            if (root == null) return -1;
            int [] secondMin = new int[] {Integer.MAX_VALUE};
            dfs(root, root.val, secondMin);
            return secondMin[0] == Integer.MAX_VALUE? -1: secondMin[0];
        }
    
        public void dfs(TreeNode root, int min, int [] secondMin) {
            if (root == null) return;
            if (root.val != min && root.val < secondMin[0])
                secondMin[0] = root.val;
            dfs(root.left, min, secondMin);
            dfs(root.right, min, secondMin);
        }
    

Log in to reply
 

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