Find All The Lonely Nodes
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 228 ms)β
| Metric | Value |
|---|---|
| Runtime | 228 ms |
| Memory | 34.3 MB |
| Date | 2021-10-02 |
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<int> GetLonelyNodes(TreeNode root) {
List<int> result = new List<int>();
helper(root, result);
return result;
}
private void helper(TreeNode root, List<int> result)
{
if (root == null)
{
return;
}
if(root.left==null && root.right!= null)
{
result.Add(root.right.val);
}
if (root.left != null && root.right == null)
{
result.Add(root.left.val);
}
helper(root.left, result);
helper(root.right, result);
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |