Binary Tree Right Side View


  • 0
    U
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            if(root==null){
                return result;
            }
            Queue<TreeNode> qu = new LinkedList<TreeNode>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            qu.offer(root);
            TreeNode temp = null;
            while(!qu.isEmpty()){
                TreeNode extractedNode = qu.poll();
                if(extractedNode.left != null){
                    queue.offer(extractedNode.left);
                }
                if(extractedNode.right != null){
                    queue.offer(extractedNode.right);
                }
                if(qu.isEmpty()){
                    result.add(extractedNode.val);
                    qu = new LinkedList<TreeNode>(queue);
                    queue = new LinkedList<TreeNode>();
                }
            }
            return result;
        }
    }

  • 0
    I

    Nice approach. Would it still make sense to replace the below? Why do you have to copy?

    qu = new LinkedList<TreeNode>(queue); -> qu = queue;


Log in to reply
 

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