力扣 199. 二叉树的右视图

题目:

力扣 199. 二叉树的右视图_第1张图片

 

分析:

层次遍历二叉树,每层的最后一个放入list链表中

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List rightSideView(TreeNode root) {
        List list=new ArrayList();
        Queue q=new LinkedList();
        q.offer(root);
        q.offer(null);
        while(q.peek()!=null){
             TreeNode t=null;
             while(q.peek()!=null){
                 t=q.poll();
                 if(t.left!=null){
                    q.offer(t.left);
                 }
                 if(t.right!=null){
                    q.offer(t.right);
                 }
             }
             q.poll();
             if(t!=null){
                list.add(t.val);
             }
             q.offer(null);
        }
        return list;
    }
}

你可能感兴趣的:(算法题,蓝桥杯,职场和发展)