Simple solution in C# using PreOrder Traversal


  • 0
    P
    public class Solution {
        public IList<IList<int>> LevelOrder(TreeNode root) {
             List<IList<int>> lst = new List<IList<int>>();
             LevelOrder(root, lst, 0);
             return lst;
        }
        
        public void LevelOrder(TreeNode root, List<IList<int>> lst, int height)
            {
                if (root == null)
                    return;
    
                if (lst.Count > height)
                {
                    lst[height].Add(root.val);
                }
                else
                {
                    lst.Add(new List<int>() { root.val });
                }
    
                LevelOrder(root.left, lst, height + 1);
                LevelOrder(root.right, lst, height + 1);
            }
    }
    

Log in to reply
 

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