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<>();
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) {
                if (node.left != null) {
                if (node.right != null) {
        return res;

Log in to reply

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