Easy to understand. BFS solution use Java


  • 0

    The idea is simple: use BFS to visit tree layer by layer, just like a normal BFS. Use queue size to know if the current TreeNode is the right most TreeNode in current layer. If it is, add it to the result list.

        if (root == null) {
            return new ArrayList<Integer>();
        }
        
        List<Integer> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) {
                    res.add(node.val);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return res;

Log in to reply
 

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