Найти два двоичных дерева структурно идентичны
Меня недавно спросили в интервью
Какой эффективный алгоритм можно найти, если два заданных двоичных дерева структурно идентичны, но не содержат контент?
a
/ \
b c
\
e
z
/ \
u v
\
t
структурно идентичны.
Следующим вопросом было выяснить, являются ли 2 двоичных дерева структурно зеркальными?
Любой указатель или помощь приветствуются.
Моя попытка была
boolean isStrucutrallyIdentitical(BinaryNode root1, BinayNode root2) {
if(root1==null && root2==null) return true;
if(root1==null || root2==null) return false;
if(root1!=null && roo2!=null) return true; // instead of value just check if its null or not
return isStrucutrallyIdentitical(root1.getLeft(), root2.getLeft()) && isStrucutrallyIdentitical(root1.getRight(), root2.getRight());
}
2 ответа
Решение
public boolean areStructuralySame(TreeNode<Integer> tree1, TreeNode<Integer> tree2) {
if(tree1 == null && tree2 == null) {
return true;
}
if(tree1 == null || tree2 == null) {
return false;
} else return (areStructuralySame(tree1.getLeft(), tree2.getLeft()) && areStructuralySame(tree1.getRight(), tree2.getRight()));
}
Это отлично работает
private static boolean compare(TNode curRoot, TNode newRoot) {
if (curRoot == null && newRoot == null) {
return true;
} else if ((curRoot == null && newRoot != null) || (curRoot != null && newRoot == null))
return false;
else {
if (compare(curRoot.left, newRoot.left) && compare(curRoot.right, newRoot.right))
return true;
return false;
}
}