如何描述和编码一个算法来检查两个二叉树是否相同?



他们的质量标准要求我使用正确的语法和写我已经尝试过的东西,但我真的没有信息。它只是让我这样做,我不知道怎么开始。

相同
binary tree please help

如果你想检查两棵树是否相同,你可以同时遍历这两棵树。当遍历两棵树时,如果其中一棵树上存在节点而另一棵树上不存在节点,则这两棵树不相同。

您可以采用这里描述的递归方法:https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/

sameTree(tree1, tree2)
1. If both trees are empty then return 1.
2. Else If both trees are non -empty
(a) Check data of the root nodes (tree1->data ==  tree2->data)
(b) Check left subtrees recursively  i.e., call sameTree( 
tree1->left_subtree, tree2->left_subtree)
(c) Check right subtrees recursively  i.e., call sameTree( 
tree1->right_subtree, tree2->right_subtree)
(d) If a,b and c are true then return 1.
3  Else return 0 (one is empty and other is not)
现在如果你想检查两棵树是否同构有很多方法可以做到这一点。为了获得较高的准确性和良好的性能,您可能会寻找某种方法来同时散列这两棵树。

最新更新