LeetCode-199-二叉树的右视图

解题思路

利用双端队列进行广度优先遍历,将每一层的最后的节点加入结果集

代码

class Solution {
    public List rightSideView(TreeNode root) {
        LinkedList result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        Deque deque = new LinkedList<>();
        deque.addLast(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            result.add(deque.getLast().val);
            for (int i = 0; i < size; i++) {
                TreeNode head = deque.removeFirst();
                if (head.left != null) {
                    deque.addLast(head.left);
                }
                if (head.right != null) {
                    deque.addLast(head.right);
                }
            }
        }
        return result;
    }
}

你可能感兴趣的:(LeetCode-199-二叉树的右视图)