C# Accepted solution using BFS


  • 0
    J

    This code is similar to the solution present within the solutions present within the discuss forum for this problem.

    Dictionary<int, IList<int>> dic = new Dictionary<int, IList<int>>();
        List<IList<int>> result = new List<IList<int>>();
        
        Queue<TreeNode> nodes = new Queue<TreeNode>();
        Queue<int> col = new Queue<int>();
        
        public IList<IList<int>> VerticalOrder(TreeNode root) 
        {
            if (root == null) return result;
            nodes.Enqueue(root);
            col.Enqueue(0);
            
            while (nodes.Count != 0)
            {
                var node = nodes.Dequeue();
                var colnum = col.Dequeue();
                if (dic.ContainsKey(colnum)) dic[colnum].Add(node.val);
                else
                {
                    var list = new List<int>();
                    list.Add(node.val);
                    dic.Add(colnum, list);
                }
                if (node.left != null)
                {
                    nodes.Enqueue(node.left);
                    col.Enqueue(colnum-1);
                }
                if (node.right != null)
                {
                    nodes.Enqueue(node.right);
                    col.Enqueue(colnum+1);
                }
            }
            var temp = dic.Keys.ToList();
            temp.Sort();
            foreach (var key in temp)
            {
                result.Add(dic[key]);
            }
            return result;
        }
    

Log in to reply
 

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