繁体   English   中英

不使用递归遍历二叉树

[英]Binary tree traversal without using recursion

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

您也许可以使用线程二叉树的变体; 使用叶节点的right链接指向遍历中的下一个节点,例如

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

叶节点C明确指向D ,它是预遍历中的下一个节点, D明确指向E 这使插入和删除操作更加麻烦,但是它使您可以轻松地进行预遍历,而无需递归并且不需要辅助堆栈。

由于预订可以通过深度优先搜索完成 ,因此可以通过这种方式完成; 请注意,深度优先搜索是一种递归方法。 就是说,我不需要通过递归函数调用来实现,而是可以通过使用堆栈作为辅助数据结构来实现,该堆栈有效地用于生成访问序列,否则将通过递归来生成该访问序列。 用伪代码,这可以按如下方式完成,其中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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM