leetcode987
public class Solution
{
private Dictionary<int, List<KeyValuePair<int,int>>> dic = new Dictionary<int, List<KeyValuePair<int, int>>>();
private void SearchTree(TreeNode root,int val=,int depth=)
{
if(root != null)
{
if(dic.ContainsKey(val))
{
dic[val].Add(new KeyValuePair<int, int>(root.val,depth));
}
else
{
dic.Add(val, new List<KeyValuePair<int, int>>());
dic[val].Add(new KeyValuePair<int, int>(root.val, depth));
}
}
if(root.left!=null)
{
SearchTree(root.left, val - ,depth+);
}
if(root.right!=null)
{
SearchTree(root.right, val + ,depth+);
}
}
public IList<IList<int>> VerticalTraversal(TreeNode root)
{
var Li = new List<IList<int>>();
SearchTree(root);
var kvpairs = dic.OrderBy(x => x.Key).ToList();
foreach(var kv in kvpairs)
{
Li.Add(kv.Value.OrderBy(x => x.Value).ThenBy(x=>x.Key).Select(x=>x.Key).ToList());
}
return Li;
}
}
这道题的描述有一些不清楚,主要是If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
这一句,应该是先按照层排序,同层的节点再按照值从小到大排序。
如果没有主意到这个问题,会出现test case 13无法通过,截图如下:
因此,关键性的代码是下面这句,先按照层次排序,再按照值排序,再选择出值部分,用一个lambda解决。
Li.Add(kv.Value.OrderBy(x => x.Value).ThenBy(x=>x.Key).Select(x=>x.Key).ToList());
leetcode987的更多相关文章
- [Swift]LeetCode987. 二叉树的垂序遍历 | Vertical Order Traversal of a Binary Tree
Given a binary tree, return the vertical order traversal of its nodes values. For each node at posit ...
随机推荐
- Ubuntu 14.04不显示标题栏和侧边栏
Ubuntu 14.04不显示标题栏和侧边栏 进入桌面后 Ctrl + Alt + F1 切换到 tty1,登录,然后运行: sudo apt-get install unity lightdm重启即 ...
- xp sql2000 安装SP4失败解决方案
环境:xp sp3 SQL: sql2000sql2000 SP4下载链接: http://www.microsoft.com/downloads/details.aspx?familyid=8E2D ...
- php的语句
1.php流程语句 1.php代码执行从上到下 2.条件语句 if else 和 switch 案例: $name=56; if($name>56) echo "hello world ...
- Windows和pthread中提供的自旋锁
Windows和POSIX中都提供了自旋锁,我们也可以通过C++11的atomic来实现自旋锁.那么两者性能上面是什么关系?先引入实现代码: #ifndef __spinlock_h__ #defin ...
- imageLoader之介绍
相信大家在学习以及实际开发中基本都会与网络数据打交道,而这其中一个非常影响用户体验的就是图片的缓存了,若是没有弄好图片缓存,用户体验会大大下降,总会出现卡顿情况,而这个问题尤其容易出现在ListVie ...
- ext.net tooltip
业务场景:需要对grid表格中指定列显示tooltip. html: <form id="form1" runat="server"> <To ...
- Linux下单独编译安装PHP扩展包
首先进入PHP源码目录,比如这个: root@vultr:~/php-/ext/soap# 运行下PHP目录下的phpize,接着就可以和普通代码一样,配置,编译,安装了(注意:有些库可能可以配置参数 ...
- protocol buf安装
1:下载安装包 $wget https://github.com/google/protobuf/archive/v2.6.1.zip $unzip protobuf-2.6.1.zip $cd pr ...
- Structrued Streaming业务数据实时分析
先启动spark-shell,记得启动nc服务 输入以下代码 scala> import org.apache.spark.sql.functions._ import org.apache.s ...
- 9 个鲜为人知的 Python 数据科学库
除了 pandas.scikit-learn 和 matplotlib,还要学习一些用 Python 进行数据科学的新技巧. Python 是一种令人惊叹的语言.事实上,它是世界上增长最快的编程语言之 ...