Solution that beats 97% of C# submissions: Simple level order traversal using List<LinkedList<int>>


  • 0
    M
    public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
        var linkedLists = new List<LinkedList<int>>();
        
        if(root != null) LevelOrderTraversal(root, linkedLists, 0, true);
        
        return linkedLists.Select(l => l.ToList() as IList<int>).ToList();
    }
    
    public void LevelOrderTraversal(TreeNode root, List<LinkedList<int>> lists, int level, bool leftToRight) {        
        if(lists.Count()-1 < level) lists.Add(new LinkedList<int>());
        
        if(leftToRight) 
            lists[level].AddLast(root.val);
        else
            lists[level].AddFirst(root.val);
        
        if(root.left != null)
            LevelOrderTraversal(root.left, lists, level+1, !leftToRight);
        
        if(root.right != null)
            LevelOrderTraversal(root.right, lists, level+1, !leftToRight);
    }

Log in to reply
 

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