Created
November 6, 2023 02:56
-
-
Save unilecs/de33a57711c2943b01f9fb65da58229f to your computer and use it in GitHub Desktop.
Задача: Поправить бинарное дерево
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
public class Program | |
{ | |
public class TreeNode | |
{ | |
public int val; | |
public TreeNode left; | |
public TreeNode right; | |
public TreeNode(int val, TreeNode left = null, TreeNode right = null) | |
{ | |
this.val = val; | |
this.left = left; | |
this.right = right; | |
} | |
} | |
public static HashSet<int> Visited = new HashSet<int>(); | |
public static TreeNode FixBinaryTree(TreeNode root) { | |
if (root == null) { | |
return null; | |
} | |
// в дереве мы начинаем обход сначала с правой стороны, | |
// поэтому если мы встретили правый узел, который уже мы обрабатывали, | |
// значит это и есть искомый дефектный узел, который нужно удалить. | |
if (root.right != null && Visited.Contains(root.right.val)) { | |
return null; | |
} | |
Visited.Add(root.val); | |
root.right = FixBinaryTree(root.right); | |
root.left = FixBinaryTree(root.left); | |
return root; | |
} | |
public static void Main() | |
{ | |
Console.WriteLine("UniLecs"); | |
// tests | |
var root1 = new TreeNode(1); | |
root1.left = new TreeNode(2); | |
root1.right = new TreeNode(3); | |
root1.left.right = root1.right; | |
var fixedRoot1 = FixBinaryTree(root1); | |
Console.WriteLine((fixedRoot1.left == null).ToString()); // true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment