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=0,int depth=0) { 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 - 1,depth+1); } if(root.right!=null) { SearchTree(root.right, val + 1,depth+1); } } 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());