如何描述和编码算法以检查两个二进制树是否相同?

发布于 2025-01-29 20:16:28 字数 152 浏览 4 评论 0原文

他们的质量标准要求我使用适当的语法并写下我已经尝试过的内容,但我确实没有信息。它只是要求我这样做,我不知道如何开始。

相同的

binary tree please help

Their quality standards require me to use proper grammar and write what I have already tried but I have really no information. It just asks me to do that and I have no idea how to start.

identical

binary tree please help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〆凄凉。 2025-02-05 20:16:28

如果要检查两棵树是否相同,则可以简单地同时穿越两棵树。在穿越两棵树时,如果一个节点存在于一棵树上,而在另一棵树上不存在,则树是不相同的。

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

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)

现在,如果您想检查两个树是否是 iNSOMORPHIC ,您可以做到多种方法。为了高准确性和良好的性能,您可能正在寻找一种用两种树木放置的方式。

If you want to check if two trees are identical, you can simply simultaneously traverse the two trees. When traversing the two trees, if a node exists on one tree but not on the other, then the trees are not identical.

You can take the recursive approach described here: 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)

Now if you want to check if two trees are isomorphic, there are a range of ways you could do that. For high accuracy and good performance you would probably be looking for some way to hash both the trees.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文