1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class BinaryTreeRightSideView { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); Deque<TreeNode> queue = new LinkedList<TreeNode>(); if (root == null) { return result; } queue.offer(root); int p = 1; int level = 0; while (!queue.isEmpty()) { TreeNode node = queue.poll(); p--; if (node.left != null) { queue.offer(node.left); level++; } if (node.right != null) { queue.offer(node.right); level++; } if (p == 0) { result.add(node.val); p = level; level = 0; } } return result; } }
|