Simple BFS => AC JAVA Solution


  • 0
    W

    Once you go down the tree the values will only get larger and larger. Explore top levels before going down.

    class Solution {
        private int min;
        
        public int findSecondMinimumValue(TreeNode root) {
            if (root == null || root.left == null) return -1;
            min = root.val;
            return bfs(root);
        }
        
        private int bfs(TreeNode root) {
            int res = Integer.MAX_VALUE;
            
            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            while (!q.isEmpty()) {
                TreeNode node = q.poll();
                if (node.val > min && node.val < res) {
                    res = node.val;
                }
                if (node.val == min && node.left != null) {
                    q.offer(node.left);
                    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.