[LeetCode]199. Binary Tree Right Side View

来源:互联网 发布:蓝巨星软件下载 编辑:程序博客网 时间:2024/05/16 14:17

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].

思路:层序遍历二叉树,把每一层的最后一个节点存进结果list中

/** * 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> res = new ArrayList<Integer>();        if (root == null) return res;        int thislevel = 1;        int nextlevel = 0;        LinkedList<TreeNode> q = new LinkedList<TreeNode>();        q.add(root);        while(q.isEmpty() == false) {            while(thislevel > 0) {                TreeNode temp = q.poll();                thislevel--;                if (thislevel == 0) res.add(temp.val);                if(temp.left != null) {                    nextlevel++;                    q.offer(temp.left);                }                if(temp.right != null) {                    nextlevel++;                    q.offer(temp.right);                }            }            thislevel = nextlevel;            nextlevel = 0;        }        return res;    }}


0 0