C# - recursive level order, then reverse result

  • 0

    The only way I can think to avoid the reverse before the return would be to do 1 pass to determine the height then use the height initialize the lists with empty lists. Then begin to fill the lists whose index you can get from the level and the max height determined before the traversal. But, this is not any better than just reversing the list at the end. Anyhow, I went with reverse, it seemed more straightforward.

        public IList<IList<int>> LevelOrderBottom(TreeNode root) 
            IList<IList<int>> lists = new List<IList<int>>();
            Level(lists, root, 0);
            return lists.Reverse().ToList();
        public void Level(IList<IList<int>> lists, TreeNode node, int level)
            if (node == null)  return;
            if (lists.Count == level) lists.Add(new List<int>());
            Level(lists, node.left, level + 1);
            Level(lists, node.right, level + 1);

Log in to reply

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