Find Leaves of Binary Tree
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 196 ms)β
| Metric | Value |
|---|---|
| Runtime | 196 ms |
| Memory | 41 MB |
| Date | 2022-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β
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |