首页 > 其他 > 详细

leetcode987

时间:2019-02-05 22:31:00      阅读:205      评论:0      收藏:0      [点我收藏+]
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());

leetcode987

原文:https://www.cnblogs.com/asenyang/p/10353207.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!