c# easy understand solution


  • 0
    Y

    Here I use 'x' and 'y' to record the position of each node and use sorted dictionaries to store the ordered node value.

    public class Solution {
        public IList<IList<int>> VerticalOrder(TreeNode root) {
            SortedDictionary<int, SortedDictionary<int, List<int>>> dict = new SortedDictionary<int, SortedDictionary<int, List<int>>>();
            IList<IList<int>> res = new List<IList<int>>{};
            helper(root, 0, 0, dict);
            foreach(var dic in dict){
                List<int> list = new List<int>();
                foreach(var item in dic.Value){
                    list.AddRange(item.Value);
                }
                res.Add(list);
            }
            return res;
        }
        
        private void helper(TreeNode node, int x, int y, SortedDictionary<int, SortedDictionary<int, List<int>>> dict){
            if(node == null) return;
            if(dict.ContainsKey(x)){
                if(dict[x].ContainsKey(y)) dict[x][y].Add(node.val);
                else dict[x].Add(y, new List<int>(){node.val});
            } else {
                dict.Add(x, new SortedDictionary<int, List<int>>());
                dict[x].Add(y, new List<int>(){node.val});
            }
            helper(node.left, x-1, y+1, dict);
            helper(node.right, x+1, y+1, dict);
            return;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.