Very Simple Java Solution using DFS (Pre-Order Traversal)


  • 0
    A
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        
        int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
        
        public int findSecondMinimumValue(TreeNode root) {
            
            computeNodeValue(root);
            
            if (second == first || second == Integer.MAX_VALUE)
                return -1;
            else
                return second;
        }
        
        private void computeNodeValue(TreeNode root) {
            
            if (root == null) return;
            
            if (root.val < first)
                first = root.val;
            
            if (root.val > first && root.val < second)
                second = root.val;
            
            computeNodeValue(root.left);
            computeNodeValue(root.right);
        }
    }
    

Log in to reply
 

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