gpt4 book ai didi

data-structures - 何时使用前序、后序和中序二叉搜索树遍历策略

转载 作者:行者123 更新时间:2023-12-03 05:08:02 26 4
gpt4 key购买 nike

我最近意识到,虽然在我的生活中使用了很多 BST,但除了中序遍历之外,我从未考虑过使用任何东西(虽然我意识到并知道让程序使用前序/后序遍历是多么容易)遍历)。

意识到这一点后,我拿出了一些旧的数据结构教科书,寻找前序和后序遍历有用性背后的推理 - 但他们没有说太多。

什么时候实际使用预购/后购有哪些示例?什么时候它比按顺序更有意义?

最佳答案

何时使用前序、中序和后序遍历策略

在了解什么情况下对二叉树使用前序、中序和后序之前,您必须准确理解每种遍历策略的工作原理。使用以下树作为示例。

树的根是7,最左边的节点是0,最右边的节点是10

enter image description here

前序遍历:

摘要:从根节点 (7) 开始,到最右边的节点 (10) 结束

遍历顺序:7, 1, 0, 3, 2, 5, 4, 6, 9, 8, 10

中序遍历:

摘要:从最左边的节点 (0) 开始,到最右边的节点 (10) 结束

遍历顺序:0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

后序遍历:

摘要:从最左边的节点 (0) 开始,以根节点 (7) 结束

遍历顺序:0, 2, 4, 6, 5, 3, 1, 8, 10, 9, 7

何时使用预购、中购或后购?

程序员选择的遍历策略取决于所设计算法的具体需求。目标是速度,因此请选择能为您带来最快节点的策略。

  1. 如果您知道在检查任何叶子之前需要探索根,那么您会选择预购,因为您将在遇到所有叶子之前遇到所有根。

  2. 如果您知道需要在任何节点之前探索所有叶子,则可以选择后序,因为您不会浪费任何时间在搜索叶子时检查根。

  3. 如果您知道树的节点具有固有的顺序,并且您希望将树展平回其原始顺序,则应使用中序遍历。这棵树将以与创建它相同的方式被压平。前序或后序遍历可能不会将树展开回用于创建它的序列。

前序、中序和后序的递归算法(C++):

struct Node{
int data;
Node *left, *right;
};
void preOrderPrint(Node *root)
{
print(root->name); //record root
if (root->left != NULL) preOrderPrint(root->left); //traverse left if exists
if (root->right != NULL) preOrderPrint(root->right);//traverse right if exists
}

void inOrderPrint(Node *root)
{
if (root.left != NULL) inOrderPrint(root->left); //traverse left if exists
print(root->name); //record root
if (root.right != NULL) inOrderPrint(root->right); //traverse right if exists
}

void postOrderPrint(Node *root)
{
if (root->left != NULL) postOrderPrint(root->left); //traverse left if exists
if (root->right != NULL) postOrderPrint(root->right);//traverse right if exists
print(root->name); //record root
}

关于data-structures - 何时使用前序、后序和中序二叉搜索树遍历策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9456937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com