1. 程式人生 > >Binary Tree Right Side View (是不是得寫篇字慶賀一下啊)

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 LinkedList<>();
        if (root == null) {
            return result;
        }
        List<List<Integer>> lists = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            lists.add(list);
        }
        for (List<Integer> list: lists) {
            result.add(list.get(list.size() - 1));
        }
        return result;
    }
}