1. 程式人生 > >199. Binary Tree Right Side View | 從右邊看二叉樹得到的集合

199. Binary Tree Right Side View | 從右邊看二叉樹得到的集合

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4]

.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

思路:廣度優先遍歷,用佇列層次遍歷,並記錄每層的個數,當遍歷到最後一個的時候就新增到結果集合中,最後返回結果。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   public List<Integer> rightSideView(TreeNode root) {
		List<Integer> list = new ArrayList<>();
		if (root == null) {
			return list;
		}
		LinkedList<TreeNode> queue = new LinkedList<>();
		queue.push(root);
		int next = 0, num = 1;
		while (!queue.isEmpty()) {
			TreeNode treeNode = queue.poll();
			num--;
			if (treeNode.left != null) {
				queue.addLast(treeNode.left);
				next++;
			}
			if (treeNode.right != null) {
				queue.addLast(treeNode.right);
				next++;
			}

			if (num == 0) {
				list.add(treeNode.val);
				num = next;
				next = 0;
			}

		}
		return list;
	}
}