二叉树的右视图-leetcode199

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

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

这又是一道二叉树分层的题目,与剑指offer中的分层输出二叉树和z字形输出二叉树类似。找到每层最后一个节点并加到list中即可。代码如下:

import java.util.concurrent.LinkedBlockingQueue;
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public static List<Integer> rightSideView(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if(root==null) return list;
        Queue<TreeNode> q=new LinkedBlockingQueue<>();
        q.add(root);
        TreeNode last=root;
        TreeNode nlast=root;
        while (!q.isEmpty()) {
            TreeNode tmp = q.poll();
            if (tmp.left != null) {
                q.offer(tmp.left);
                nlast = tmp.left;
            }
            if (tmp.right != null) {
                q.offer(tmp.right);
                nlast = tmp.right;
            }
            if (tmp == last) {
                list.add(last.val);
                last = nlast;
            }
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/baidu_38815750/article/details/84758671
今日推荐