My Java BFS Solution Sharing


  • 0
    F
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            if(root == null) return result;
            queue.offer(root);
            int count = 0, levelSum = 1, nextSum = 0;
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                if(count == 0) result.add(node.val);
                if(node.right != null) {
                    queue.offer(node.right);
                    nextSum++;
                } 
                if(node.left != null) {
                    queue.offer(node.left);
                    nextSum++;
                }
                count++;
                if(count == levelSum) {
                    count = 0;
                    levelSum = nextSum;
                    nextSum = 0;
                }
            }
            return result;
        }
    }

Log in to reply
 

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