C# - Simple solution


  • 0
    K
    • Traverse both left and right nodes at a time
    • Save each level results in dictionary
    • Since the tree is traversed both left and right in single call for each level, values are read in the intended order

    Dictionary<int, IList<int>> levelsDict = new Dictionary<int, IList<int>>();
    public IList<IList<int>> LevelOrder(TreeNode root)
    {
    if (root == null)
    return new List<IList<int>>();

            levelsDict.Add(-1, new List<int>(new int[] { root.val }));
            LevelOrderInternal(root.left, root.right, 0);
            return levelsDict.Values.ToList();
        }
        private int LevelOrderInternal(TreeNode left, TreeNode right, int level)
        {
            if (left == null && right == null)
                return level;
    
            IList<int> nums = null;
    
            if (!levelsDict.TryGetValue(level, out nums))
            {
                nums = new List<int>();
                levelsDict.Add(level, nums);
            }
    
            int leftLevel = level;
            int rightLevel = level;
            if (left != null)
            {
                nums.Add(left.val);
                leftLevel = leftLevel + 1;
                leftLevel = LevelOrderInternal(left.left, left.right, leftLevel);
            }
            if (right != null)
            {
                nums.Add(right.val);
                rightLevel = rightLevel + 1;
                rightLevel = LevelOrderInternal(right.left, right.right, rightLevel);
            }
    
            level = Math.Max(leftLevel, rightLevel);
            return level;
        }
    


Log in to reply
 

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