Skip to main content

Find Leaves of Binary Tree

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 196 ms)​

MetricValue
Runtime196 ms
Memory41 MB
Date2022-01-31
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public IList<IList<int>> FindLeaves(TreeNode root) {
List<IList<int>> result = new List<IList<int>>();
Height(root, result);
return result;
}

private int Height(TreeNode root, List<IList<int>> result)
{
if(root==null)
{
return -1;
}
int height = 1 + Math.Max(Height(root.left, result), Height(root.right, result));
while(result.Count <= height)
{
result.Add(new List<int>());
}
result[height].Add(root.val);
root.left = null;
root.right = null;
return height;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2022-01-31) β€” 201 ms, 41.3 MB​

/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public IList<IList<int>> FindLeaves(TreeNode root) {
List<IList<int>> result = new List<IList<int>>();
Height(root, result);
return result;
}

private int Height(TreeNode root, List<IList<int>> result)
{
if(root==null)
{
return -1;
}
int height = 1 + Math.Max(Height(root.left, result), Height(root.right, result));
while(result.Count < height+1)
{
result.Add(new List<int>());
}
result[height].Add(root.val);
root.left = null;
root.right = null;
return height;
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed