二叉树遍历而不使用递归

时间:2015-03-25 19:34:18

标签: c data-structures tree binary-tree

任何人都可以帮助创建二叉树并在c中对二叉树进行非递归前序遍历吗?

3 个答案:

答案 0 :(得分:1)

您可以使用threaded binary tree的变体;使用叶节点的right链接指向遍历中的下一个节点,类似于

                    +---+
                    | A |
                    +---+
                   /     \
              +---+       +---+
              | B |       | E |
              +---+       +---+
             /     \      ^
        +---+       +---+ |
        | C |       | D | |
        +---+       +---+ |
            |       ^   | |
            +-------+   +-+

叶节点C明确指向D,它是前序导线中的下一个节点,D明确指向E。这使得插入和删除更加困难,但它为您提供了一个简单的前序遍历,没有递归和没有辅助堆栈。

答案 1 :(得分:0)

由于预订可以通过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;
}

答案 2 :(得分:0)

我找到了这段代码:

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