簡體   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