🌗 199. 二叉树的右视囟

吞䜛童子2022幎10月10日
  • algorithm
  • tree
小于 1 分钟

🌗 199. 二叉树的右视囟

隟床: 🌗

问题描述

img_3.png


解法

/**
 * 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<Integer> rightSideView(TreeNode root) {
        // 思路
        // 层序
        List<Integer> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        // root != null
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int len = queue.size();
            for(int i = 0; i < len; i ++) {
                TreeNode cur = queue.poll();
                if(i == len - 1) {
                    res.add(cur.val);
                }
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }
        return res;
    }
}

蟓出

img_2.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou