199.Binary Tree Right Side View
发布时间:2020-12-14 04:15:40 所属栏目:大数据 来源:网络整理
导读: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.Example:Input:?[ 1,2,3, null ,5,4 ]Output:?[ 1,4 ]Explanation: 1 --- / 2 3 --- 5 4 --- /** * Def
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. Example: Input:?[1,2,3,null,5,4] Output:?[1,4] Explanation: 1 <--- / 2 3 <--- 5 4 <--- /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> rightSideView(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); List<Integer> result = new ArrayList<>(); if(root == null) return result; queue.offer(root); while (!queue.isEmpty()){ int size = queue.size(); for (int i = 0; i < size; i++){ TreeNode cur = queue.poll(); if(i == 0){ result.add(cur.val); } if(cur.right != null) queue.offer(cur.right); if(cur.left != null) queue.offer(cur.left); } } return result; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |