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.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1<--- /\ 23<--- \\ 54<---
難度: medium
題目: 給定二叉樹,想像一下你站在樹的右邊,返回能看到的所有結點,結點從上到下輸出。
思路:層次遍歷,BFS
Runtime: 1 ms, faster than 79.74% of Java online submissions for Binary Tree Right Side View.
Memory Usage: 34.7 MB, less than 100.00% of Java online submissions for Binary Tree Right Side View.
/** * 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> result = new ArrayList<>(); if (null == root) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { int qSize = queue.size(); for (int i = 0; i < qSize; i++) { TreeNode node = queue.poll(); if (node.right != null) { queue.add(node.right); } if (node.left != null) { queue.add(node.left); } if (0 == i) { result.add(node.val); } } } return result; } }