C# Simple Recursive DFS with Reverse() afterwards (beats 90.14%)


  • 0
    T
    public class Solution {
        
        IList<IList<int>> Result;
        
        void Dfs(TreeNode node, int level)
        {
            if(node == null) return;
            
            if(Result.Count() <= level) Result.Add(new List<int>());
            Result[level].Add(node.val);
            
            Dfs(node.left, level + 1);
            Dfs(node.right, level + 1);
        }
        
        public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
            Result = new List<IList<int>>();
            Dfs(root, 0);
            
            for(var i=1; i<Result.Count(); i+=2)
            {
                Result[i] = Result[i].Reverse().ToList();
            }
            
            return Result;
        }
    }
    

Log in to reply
 

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