Naive Solution: level order traversal with queue


  • 0
    M
    public List<Integer> rightSideView(TreeNode root) {
        //traverse by order, then return last element of every sub list
        if (root == null) return new LinkedList<>();
        List<List<Integer>> allLevels = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> thisLevel = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode current = queue.poll();
                if (current.left != null) {
                    queue.offer(current.left);
                    thisLevel.add(current.left.val);
                }
                if (current.right != null) {
                    queue.offer(current.right);
                    thisLevel.add(current.right.val);
                }
            }
            allLevels.add(thisLevel);
        }
        List<Integer> ret = new LinkedList<>();
        ret.add(root.val);
        for (List<Integer> list : allLevels) {
            if (list.size() > 0) {
                int rightValue = list.get(list.size()-1);
                ret.add(rightValue);
            }
        }
        return ret;
    }

Log in to reply
 

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