Very Simple BFS solution C#


  • 0
    public IList<double> AverageOfLevels(Treenode root)
    {
        List<double> res = new List<double>();
        if (root == null) return res;
        Queue<Treenode> q = new Queue<Treenode>();
        q.Enqueue(root);
        while (q.Any()) //while q is not empty
        {
            int count = q.Count;
            double sum = 0;
            for (int i = 0; i < count; i++)
            {
                Treenode curr = q.Dequeue();
                sum += curr.data;
                if (curr.left != null) q.Enqueue(curr.left);
                if (curr.right!= null) q.Enqueue(curr.right);
            }
            res.Add(sum/count);
        }
        return res;
    }
    

Log in to reply
 

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