题目
1- 思路
2- 实现
⭐199. 二叉树的右视图——题解思路
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null){
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
List<Integer> iterm = new ArrayList<>();
while(len>0){
TreeNode nowNode = queue.poll();
iterm.add(nowNode.val);
if(nowNode.left!=null){
queue.offer(nowNode.left);
}
if(nowNode.right!=null){
queue.offer(nowNode.right);
}
len--;
}
res.add(iterm.get(iterm.size()-1));
}
return res;
}
}
3- ACM 实现
public class leftView {
static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(){}
TreeNode(int x){
val = x;
}
}
public static TreeNode build(Integer[] nums){
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(nums[0]);
queue.offer(root);
int index = 1;
while (!queue.isEmpty()){
TreeNode nowNode = queue.poll();
if(index<nums.length && nums[index]!=null){
nowNode.left = new TreeNode(nums[index]);
queue.offer(nowNode.left);
}
index++;
if(index<nums.length && nums[index]!=null){
nowNode.right = new TreeNode(nums[index]);
queue.offer(nowNode.right);
}
index++;
}
return root;
}
public static List<Integer> leftView(TreeNode root){
List<Integer> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
int len = queue.size();
List<Integer> iterm = new ArrayList<>();
while(len>0){
TreeNode nowNode = queue.poll();
iterm.add(nowNode.val);
if(nowNode.left!=null){
queue.offer(nowNode.left);
}
if(nowNode.right!=null){
queue.offer(nowNode.right);
}
len--;
}
res.add(iterm.get(iterm.size()-1));
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
input = input.replace("[","");
input = input.replace("]","");
String[] parts = input.split(",");
Integer[] nums = new Integer[parts.length];
for(int i = 0 ; i < parts.length;i++){
if(parts[i].equals("null")){
nums[i] = null;
}else{
nums[i] = Integer.parseInt(parts[i]);
}
}
TreeNode root = build(nums);
List<Integer> forRes = leftView(root);
System.out.println(forRes.toString());
}
}