Day 53
题目描述
思路
采取层序遍历,利用一个high的队列来保存每个节点的高度,highb和y记录上一个节点的高度和节点,在队列中,如果队列中顶部元素的高度大于上一个节点的高度,说明上一个节点就是上一层中最右边的元素,加入数组即可,同时最后需要处理最后一个元素,因为最后一个元素没有能比较的了,需要手动加入数组。
/**
* 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>list=new ArrayList<Integer>();
if(root==null){
return list;
}
Queue<TreeNode> stack=new LinkedList<>();
Queue<Integer> high=new LinkedList<>();
stack.offer(root);
high.offer(0);
TreeNode x=root;
TreeNode y=root;
int highb=0;
while(!stack.isEmpty()){
if(high.peek()>highb){
list.add(y.val);
}
y=stack.peek();
highb=high.peek();
x=stack.poll();
high.poll();
if(x.left!=null){
stack.offer(x.left);
high.offer(highb+1);
}
if(x.right!=null){
stack.offer(x.right);
high.offer(highb+1);
}
}
list.add(x.val);
return list;
}
}