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 ...
随机推荐
- STL基础--算法(修改数据的算法)
修改元素的算法 copy, move, transform, swap, fill, replace, remove vector<int> vec = {9,60,70,8,45,87, ...
- What does "exceeded limit of maxWarmingSearchers=X" mean?
Whenever a commit happens in Solr, a new "searcher" (with new caches) is opened, "war ...
- Android Studio 增加函数注释模板
此篇文章主要介绍如何在Android Studio中函数如何添加注释,使其和eclipse一样方便的添加注释 Android Studio默认函数注释为 /** * */ 下面方法将要改为如下格式 / ...
- 将Json对象数组转化成JS Array数组
private format(cards:any):Array<any>{ var result = new Array(); cards.forEach(element => { ...
- Android开发之Activity生命周期篇
一.Activity: 1.Activity:Activity是一个与用记交互的系统模块,几乎所有的Activity都是和用户进行交互的. 2.在Android中Activity主要是用来做控制的,它 ...
- bzoj2856: [ceoi2012]Printed Circuit Board
Description 给出一个N个顶点的简单多边形,对于每个顶点,假如它和原点连成的线段只在这个顶点处和多边形相交,就称为满足要求的顶点.你的任务是输出所有满足要求的顶点编号. Input 第一行一 ...
- 《Java并发编程实战》笔记-状态依赖方法的标准形式
void stateDependentMethod() throws InterruptedException { //必须通过一个锁来保护条件谓词 synchronized(lock) { whil ...
- python 正则表达提取方法 (提取不来的信息print不出来 加个输出type 再print信息即可)
1,正则表达提取 (findall函数提取) import re a= "<div class='content'>你大爷</div>"x=re.finda ...
- 信息安全-加密:RAS 加密
ylbtech-信息安全-加密:RAS 加密 1.返回顶部 1. RSA 是不对称的加密(加密密钥和解密密钥不同 其中 一个为公钥,一个为私钥): 公钥和私钥的产生是基于一对很大的素数(十进制来说 ...
- 【ZZ】号称“开发者神器”的GitHub,到底该怎么用?
号称“开发者神器”的GitHub,到底该怎么用? https://mp.weixin.qq.com/s/zpKOBMKWckY05Mv_B28RgQ A developer’s introductio ...