zoukankan      html  css  js  c++  java
  • 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=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());
  • 相关阅读:
    Thinkhphp5控制器调用的Model层的方法总结
    js数组与字符串的相互转换方法
    oop中 限制文件类型和大小
    php常用内置函数
    PHP 面向对象
    微信JSSDK开发
    PHPExcel探索之旅
    php操作Excel
    百度地图和高德地图的API视频教程
    手机号码归属地查询(免费)
  • 原文地址:https://www.cnblogs.com/asenyang/p/10353207.html
Copyright © 2011-2022 走看看