【发布时间】:2015-03-25 19:34:17
【问题描述】:
任何人都可以帮助创建一个二叉树并在 c 中对二叉树进行非递归的前序遍历吗?
【问题讨论】:
-
使用本地动态栈。
标签: c data-structures tree binary-tree
任何人都可以帮助创建一个二叉树并在 c 中对二叉树进行非递归的前序遍历吗?
【问题讨论】:
标签: c data-structures tree binary-tree
您也许可以使用threaded binary tree 的变体;使用叶节点的right 链接指向遍历中的下一个节点,类似于
+---+
| A |
+---+
/ \
+---+ +---+
| B | | E |
+---+ +---+
/ \ ^
+---+ +---+ |
| C | | D | |
+---+ +---+ |
| ^ | |
+-------+ +-+
叶节点C显式指向D,即前序遍历中的下一个节点,D显式指向E。这使得插入和删除更加痛苦,但它为您提供了一个简单的前序遍历,无需递归和辅助堆栈。
【讨论】:
由于可以通过depth-first search进行预订,所以可以通过这种方式进行;请注意,深度优先搜索是一种递归方法。话虽如此,我不需要通过递归函数调用来实现,而是可以通过使用堆栈作为辅助数据结构来实现,它有效地用于生成访问序列,否则将由递归生成。在伪代码中,可以按如下方式完成,其中visit 将是实际访问节点的函数。
push the root of the tree to the stack;
while (stack is not empty)
{
Node = top of stack;
visit Node;
if Node has unvisited left child
push left child of Node
else if right child of Node is Not visited
push right child of Node
else
pop;
}
【讨论】:
我找到了这段代码:
void iterativePreorder(node *root)
{
// Base Case
if (root == NULL)
return;
// Create an empty stack and push root to it
stack<node *> nodeStack;
nodeStack.push(root);
/* Pop all items one by one. Do following for every popped item
a) print it
b) push its right child
c) push its left child
Note that right child is pushed first so that left is processed first */
while (nodeStack.empty() == false)
{
// Pop the top item from stack and print it
struct node *node = nodeStack.top();
printf ("%d ", node->data);
nodeStack.pop();
// Push right and left children of the popped node to stack
if (node->right)
nodeStack.push(node->right);
if (node->left)
nodeStack.push(node->left);
}
}
这里: http://www.geeksforgeeks.org/iterative-preorder-traversal/
我知道这段代码是用 C++ 编写的,但您可以在 C 中创建一组简单的函数堆栈来绕过这个问题。
如果需要,此链接也可以提供帮助:
http://groups.csail.mit.edu/graphics/classes/6.837/F04/cpp_notes/stack1.html
【讨论】: