JAVA DFS solution 3ms


  • 0
    Z
    1. the min num of the tree is the ROOT.VAL
    2. the variable "min" represents the return value
    3. save the max value when doing dfs and check if max == ROOT.VAL, which means all the nums in the tree are the same.
    class Solution {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        public int findSecondMinimumValue(TreeNode root) {
            max = root.val;
            min = Integer.MAX_VALUE;
            dfs(root);
            return max == root.val ? -1 : min;
        }
        
        void dfs(TreeNode root){
            if(root.left != null){
                if(root.val != root.left.val) {
                    min = Math.min(min, root.left.val);
                    max = Math.max(min, root.left.val);
                }
                if(root.val != root.right.val) {
                    min = Math.min(min, root.right.val);
                    max = Math.max(min, root.right.val);
                }
                dfs(root.left);
                dfs(root.right);
            }
        }
    }
    

Log in to reply
 

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