Skip to main content

Correct a Binary Tree

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

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

MetricValue
Runtime263 ms
Memory44.7 MB
Date2022-01-13
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 {
private List<int> visited = new List<int>();

public TreeNode CorrectBinaryTree(TreeNode root) {
if(root == null) return null;
if(root.right != null && visited.Contains(root.right.val))
{
return null;
}

visited.Add(root.val);
root.right = CorrectBinaryTree(root.right);
root.left = CorrectBinaryTree(root.left);

return root;

}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed