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.
For example:
Given the following binary tree,
1 <—
/ \
2 3 <—
\ \
5 4 <—
You should return [1, 3, 4].
题目的含义是:从右边看,我们能看到的节点有哪些,相当于几何中投影的概念。
解题思路:1)深度遍历,先记录右边节点的最大高度。只有大于最大高度的节点才能打印出来。(我们自己思维去判断的时候,应该更倾向这种逻辑)
2)层次遍历,将最右边的节点存入list表中。这种想法写程序更容易理解。
实现1)思路代码如下所示:
public List<Integer> rightSideView(TreeNode root) {
Stack<TreeNode> stack=new Stack<TreeNode>();
Stack<TreeNode> stack1=new Stack<TreeNode>();//存储所有的节点,用来计算节点所在的高度
List<Integer> list=new ArrayList<Integer>();
TreeNode current=root;
int curHeight=1;
int rightHeight=0;
while(current!=null||!stack.isEmpty())
{
if(current!=null)
{
if(curHeight>rightHeight)
{
list.add(current.val);
}
stack.push(current);
stack1.push(current);
current=current.right;
++curHeight;
}else
{
current=stack.pop();
//计算当前current节点所在的height值
while(!stack1.isEmpty())
{
if(stack1.peek()==current)
{
curHeight=stack1.size();
if(curHeight>rightHeight)rightHeight=curHeight;
break;
}
stack1.pop();
}
current=current.left;
++curHeight;
}
}
return list;
}
实现2)思路程序如下:
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
if(root==null)return list;
Queue<TreeNode> queue=new LinkedList<TreeNode>();
TreeNode current=root;
queue.offer(current);
queue.offer(null);//相当于用null来做每层节点的间隔符
while(!queue.isEmpty())
{
current=queue.poll();
if(current!=null)
{
if(queue.peek()==null)
{
list.add(current.val);
}
if(current.left!=null)queue.add(current.left);
if(current.right!=null)queue.add(current.right);
}else
{
if(queue.isEmpty())
{
break;
}else
{
queue.add(null);
}
}
}
return list;
}
时间: 2024-10-23 05:23:35