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 ...
随机推荐
- googletest基本测试宏
还不知道googletest基本使用方法的请参看前一篇blog 使用googletest进行C++单元测试 本篇仍然使用testStack测试文件进行测试,测试代码如下 #include <g ...
- ubuntu16.04下sublime text 3之安装和配置
1.安装方法 1)使用ppa安装 sudo add-apt-repository ppa:webupd8team/sublime-text-3 sudo apt-get update sudo apt ...
- Spring-framework应用程序启动loadtime源码分析笔记(三)——@KafkaListener
org.springframework.context.annotation.ConfigurationClassParser.getConfigurationClasses()读所有@Configu ...
- PAT 乙级 1026 程序运行时间(15) C++版
1026. 程序运行时间(15) 时间限制 200 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 要获得一个C语言程序的运行时间, ...
- 量化交易(Quantitative Trading)
什么是量化交易 量化交易是指借助现代统计学和数学的方法,利用计算机技术来进行交易的证券投资方式.量化交易从庞大的历史数据中海选能带来超额收益的多种“大概率”事件以制定策略,用数量模型验证及固化这些规律 ...
- 科学-天文学-天文观测站:TMT(红外天文望远镜)
ylbtech-科学-天文学-天文观测站:TMT(红外天文望远镜) 30米望远镜(Thirty Meter Telescope,TMT) 系由美国加州大学和加州理工学院负责研制的新一代地基巨型光学-红 ...
- dspmq dspmqver command not found(dspmq命令找不到,dspmqver主安装目录设置不正确
[root@rhv6-64b ~]# su - mqm -bash-4.1$ dspmq -bash: dspmq: command not found(dspmq命令找不到) -bash-4.1$ ...
- css实战——第一天
1. 开发前的准备 1.1配置开发环境 sublime webstorm vscode Hbuilder atom 1.2建立项目文件夹 主页或是首页 index.html d ...
- fastclick.js解决移动端(ipad)点击事件反应慢问题
参考http://blog.csdn.net/xjun0812/article/details/64919063 http://www.jianshu.com/p/16d3e4f9b2a9 问题的发现 ...
- VMware虚拟机上配置nginx后,本机无法访问问题
nginx装在CentOS上,用本机访问虚拟机的时候却出现了不能访问的问题,查了资料以后,原来是防火墙的问题.具体情况如下:防火墙可以ping通虚拟机,虚拟机也可以ping通防火墙.接着检查了服务器端 ...