C#: Intuitive recursive solution using tree traversal. (Accepted)

  • 0
    public class Solution {
        public IList<IList<int>> LevelOrder(TreeNode root)
            Dictionary<int, List<int>> levelMap = new Dictionary<int, List<int>>();  //Map that will store level -> values mapping. (can be done without this)
            LevelOrderHelper(root, 0, ref levelMap);   //Helper to fillout levelMap recursively.
            IList<IList<int>> levelOrderResult = new List<IList<int>>(levelMap.Count);  //Result.
            foreach(int key in levelMap.Keys)   //Converting levelMap to levelOrderResult.
                levelOrderResult.Add(new List<int>(levelMap[key]));
            return levelOrderResult;
        private static void LevelOrderHelper(TreeNode root, int level, ref  Dictionary<int, List<int>> levelMap)
            if (null == root) return;
            if (!levelMap.Keys.Contains(level)) levelMap[level] = new List<int>();  //Creating an entry for level to hold values if it doesn't exists.
            levelMap[level].Add(root.val);  //Adding the value corresponding to the level in the levelMap.
            LevelOrderHelper(root.left, level + 1, ref levelMap);   //Increasing the level number when going to childrens.
            LevelOrderHelper(root.right, level + 1, ref levelMap);

Log in to reply

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