Skip to main content

Find All The Lonely Nodes

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

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

MetricValue
Runtime228 ms
Memory34.3 MB
Date2021-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​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed