5 Line Traversal Solution in Java


  • 0

    We know the root.val is always the minimal node in given tree. Therefore, we just need to traversal the tree and find the second minimal node.

    public int findSecondMinimumValue(TreeNode root) {
            int res = traversal(root, root.val, Integer.MAX_VALUE);
            return res == Integer.MAX_VALUE ? -1 : res;
    }
    
    private int traversal(TreeNode node, int min, int min2) {
            if (node == null) return min2;
            if (node.val < min2 && node.val > min) min2 = node.val;
            return Math.min(traversal(node.left, min, min2), traversal(node.right, min, min2));
    }
    

  • 0

    Iterative version:

    public int findSecondMinimumValue(TreeNode root) {
            if (root == null) return -1;
            int min = root.val, res = Integer.MAX_VALUE;
            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            while (!q.isEmpty()) {
                TreeNode node = q.poll();
                if (node.val < res && node.val > min) res = node.val;
                if (node.left != null) q.offer(node.left);
                if (node.right != null) q.offer(node.right);
            }
            return res == Integer.MAX_VALUE ? -1 : res;
    }
    

Log in to reply
 

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