Very easy to understand BSF traversal in Java


  • 0
    B

    Easy to understand BSF traversal in Java.
    Use BSF level traversal and find the 2nd smallest node value.

    public int findSecondMinimumValue(TreeNode root) {
            if (root == null) return -1;
            
            int min = root.val;
            int secondMin = Integer.MAX_VALUE;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root); 
            while (!queue.isEmpty()) {
            	int size = queue.size();  
    	        for (int i = 0; i < size; i++) {
    	            TreeNode curr = queue.poll(); 
    	            if (curr.val > min && curr.val < secondMin) {
    	                secondMin = curr.val; 
    	            }
    	            if (curr.left != null) queue.offer(curr.left);
    	            if (curr.right != null) queue.offer(curr.right);
    	        }
            }
            
            return secondMin == Integer.MAX_VALUE ? -1 : secondMin;
        }
    

Log in to reply
 

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