问题描述
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/
2 3 <---
5 4 <---
代码
/**
* 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) {
if(root==null)
return new ArrayList<Integer>();
Queue<TreeNode> q=new LinkedList<TreeNode>();
Queue<Integer> q2=new LinkedList<Integer>();
List<Integer> list=new ArrayList<Integer>();
int last=1;
TreeNode lastT=root;
q.add(root);
q2.add(1);
while(q.size()>0) {
TreeNode p=q.poll();
int temp=q2.poll();
if(temp!=last) {
list.add(lastT.val);
last=temp;
}
lastT=p;
if(q.size()==0&&p.left==null&&p.right==null)
{
list.add(lastT.val);
return list;
}
if(p.left!=null)
{
q.add(p.left);
q2.add(temp+1);
}
if(p.right!=null)
{
q.add(p.right);
q2.add(temp+1);
}
}
return list;
}
}