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());
  • 相关阅读:
    防止sql注入的方法
    二叉树的LCA(最近公共祖先)算法
    二叉树的计算
    @RestController和@Controller注解的区别
    单调栈与单调队列
    java中删除list指定元素遇到的问题
    随机打乱数组
    Mysql基本操作
    二叉树的构建
    synchronized修饰方法和对象的区别
  • 原文地址:https://www.cnblogs.com/asenyang/p/10353207.html
Copyright © 2011-2022 走看看