Java preorder based solution


  • 0
    B

    This solution is based on preorder traversal. Time complexity should be O(n), where n is the total number of nodes in the binary tree.

    class Solution {
        int first;
        int second;
        public int findSecondMinimumValue(TreeNode root) {
            if(root == null)
                return -1;
            first = root.val;
            second = root.val;
            update(root);
            return second == first?-1:second;
        }
        
        public void update(TreeNode node){
            if(node == null)
                return;
            if(node.left!=null && node.right != null)
                node.val = Math.min(node.left.val, node.right.val);
            if(node.val <= first)
                first = node.val;
            else if(node.val <= second || second == first)
                second = node.val;
            update(node.left);
            update(node.right);
        }
    }
    

Log in to reply
 

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