Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created November 6, 2023 02:56
Show Gist options
  • Save unilecs/de33a57711c2943b01f9fb65da58229f to your computer and use it in GitHub Desktop.
Save unilecs/de33a57711c2943b01f9fb65da58229f to your computer and use it in GitHub Desktop.
Задача: Поправить бинарное дерево
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