首页 > 其他 > 详细

leetocde_Binary Tree Right Side View

时间:2015-04-08 21:36:17      阅读:180      评论:0      收藏:0      [点我收藏+]

描述:

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].

思路:

按层序遍历的思路,每次只保存该层的最后一个元素即可。

代码:

public List<Integer> rightSideView(TreeNode root) {
        List<Integer>listReturn=new ArrayList<Integer>();
        if(root==null)
        	return listReturn;
        List<TreeNode>list=new ArrayList<TreeNode>();
        List<TreeNode>temp=new ArrayList<TreeNode>();
        list.add(root);
        TreeNode node=null;
        listReturn.add(root.val);
        while(list.size()!=0)
        {
        	for(int i=0;i<list.size();i++)
        	{
        		node=list.get(i);
        		if(node.left!=null)
        			temp.add(node.left);
        		if(node.right!=null)
        			temp.add(node.right);
        	}
        	if(temp.size()>0)
        		listReturn.add(temp.get(temp.size()-1).val);
        	list.clear();
            list=temp;
        	temp=new ArrayList<TreeNode>();
        }
	    return listReturn;
   }

结果:

技术分享

leetocde_Binary Tree Right Side View

原文:http://blog.csdn.net/mnmlist/article/details/44945941

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!