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());
  • 相关阅读:
    iphone 自学常用网址
    @ApiParam @RequestParam @PathVariable 用法
    @RestController 与 @Controller 注解区别
    Java:post请求
    Java:清空文件内容
    Java:追加文件内容
    Java:获取文件内容
    Java:Md5加密
    Java:获取IP地址
    docker:安装tomcat
  • 原文地址:https://www.cnblogs.com/asenyang/p/10353207.html
Copyright © 2011-2022 走看看