BFS, easy understandable java


  • 0
    N
    /**
     * Definition for a binary tree node.
     * 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> list = new ArrayList<Integer>();
            
            if(root == null){
                return list;
            }
            
            int qsize = 0;//qsize to record the number of TreeNodes in current level
            
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            
            queue.add(root);
            
            while(!queue.isEmpty()){
                //qsize to record the number of TreeNodes in current level
                qsize = queue.size();
                
                list.add(queue.peek().val);//always add the right most TreeNode.val
                
                while(qsize >= 1){
                    TreeNode cur = queue.poll();
                    if(cur.right != null){
                        queue.add(cur.right);
                    }
                    if(cur.left != null){
                        queue.add(cur.left);
                    }
                    qsize--;
                }
            }
            return list;
        }
    }
    

Log in to reply
 

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