- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我最近意识到,虽然在我的生活中使用了很多 BST,但除了中序遍历之外,我从未考虑过使用任何东西(虽然我意识到并知道让程序使用前序/后序遍历是多么容易)遍历)。
意识到这一点后,我拿出了一些旧的数据结构教科书,寻找前序和后序遍历有用性背后的推理 - 但他们没有说太多。
什么时候实际使用预购/后购有哪些示例?什么时候它比按顺序更有意义?
最佳答案
在了解什么情况下对二叉树使用前序、中序和后序之前,您必须准确理解每种遍历策略的工作原理。使用以下树作为示例。
树的根是7,最左边的节点是0,最右边的节点是10。
前序遍历:
摘要:从根节点 (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
程序员选择的遍历策略取决于所设计算法的具体需求。目标是速度,因此请选择能为您带来最快节点的策略。
如果您知道在检查任何叶子之前需要探索根,那么您会选择预购,因为您将在遇到所有叶子之前遇到所有根。
如果您知道需要在任何节点之前探索所有叶子,则可以选择后序,因为您不会浪费任何时间在搜索叶子时检查根。
如果您知道树的节点具有固有的顺序,并且您希望将树展平回其原始顺序,则应使用中序遍历。这棵树将以与创建它相同的方式被压平。前序或后序遍历可能不会将树展开回用于创建它的序列。
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/
我是一名优秀的程序员,十分优秀!