C# - recursive DFS - 10 lines


  • 0
        public IList<IList<int>> FindLeaves(TreeNode root) 
        {
            IList<IList<int>> levels = new List<IList<int>>();
            Add(root, levels);
            return levels;
        }
        
        public int Add(TreeNode node, IList<IList<int>> levels)
        {
            if (node == null) return 0;
            int level = 1 + Math.Max(Add(node.left, levels), Add(node.right, levels));
            if (levels.Count < level) levels.Add(new List<int>());
            levels[level - 1].Add(node.val);
            return level;
        }
    

  • 0

    @jdrogin Great solution.


Log in to reply
 

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