Java dfs with explanation


  • 1

    Root always has minimu value;

    Since node.val = min (node.left.val, node.right.val),
    when node.val != root.val, we don't need to check its children anymore.

    class Solution {
        int minVal;
        long second;
        
        public int findSecondMinimumValue(TreeNode root) {
            if(root == null) return -1;
            minVal = root.val;
            second = Long.MAX_VALUE;
            dfs(root);
            return second == Long.MAX_VALUE ? -1 : (int) second;
        }
        
        private void dfs(TreeNode root){
            if (root.val != minVal){
                second = Math.min(second, root.val);
                return;
            }
            if (root.left != null)
                dfs(root.left);
            if (root.right != null)
                dfs(root.right);
        }
    }
    

Log in to reply
 

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