3ms Level Order Traversal Java Solution | Easy to understand


  • 0
    M
    public List<Integer> rightSideView(TreeNode root) {
            
            List<Integer> rightView = new ArrayList<Integer>();
            Queue<TreeNode> level_nodes = new LinkedList<TreeNode>();
            if (root == null) {
                return rightView;
            }
            level_nodes.add(root);
            
            while(!level_nodes.isEmpty()) {
                int size_of_this_level = level_nodes.size();
                for (int idx = 0; idx < size_of_this_level; idx++) {
                    if (level_nodes.peek().left != null) level_nodes.add(level_nodes.peek().left);
                    if (level_nodes.peek().right != null) level_nodes.add(level_nodes.peek().right);
                    root = level_nodes.remove(); 
                }
                rightView.add(root.val);
            }
            return rightView;
        }
    

Log in to reply
 

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