C 不使用递归的二叉树遍历

C 不使用递归的二叉树遍历,c,data-structures,tree,binary-tree,C,Data Structures,Tree,Binary Tree,任何人都可以帮助创建一个二叉树并在c中对二叉树进行非递归的预序遍历吗?因为预序可以通过来完成,所以可以通过这种方式来完成;请注意,深度优先搜索是一种递归方法。也就是说,我不需要通过递归函数调用来实现,但可以通过使用堆栈作为辅助数据结构来实现,它有效地用于生成访问序列,否则将通过递归生成访问序列。在伪代码中,这可以按如下方式完成,其中visit将是实际访问节点的函数 push the root of the tree to the stack; while (stack is not empty)

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

因为预序可以通过来完成,所以可以通过这种方式来完成;请注意,深度优先搜索是一种递归方法。也就是说,我不需要通过递归函数调用来实现,但可以通过使用堆栈作为辅助数据结构来实现,它有效地用于生成访问序列,否则将通过递归生成访问序列。在伪代码中,这可以按如下方式完成,其中
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);
    }
}
void iterativePreorder(节点*根)
{
//基本情况
if(root==NULL)
返回;
//创建一个空堆栈并将根推送到它
堆栈节点堆栈;
nodeStack.push(根);
/*逐个弹出所有项目。对每个弹出的项目执行以下操作
a) 打印出来
b) 推它右边的孩子
c) 推它左边的孩子
请注意,首先推送右子对象,以便首先处理左子对象*/
while(nodeStack.empty()==false)
{
//从堆栈中弹出顶部项目并打印它
struct node*node=nodeStack.top();
printf(“%d”,节点->数据);
nodeStack.pop();
//将弹出节点的左右子节点推送到堆栈
如果(节点->右侧)
nodeStack.push(节点->右侧);
如果(节点->左)
nodeStack.push(节点->左);
}
}
在这里:

<>我知道这个代码是C++的,但是你可以在C中创建一个简单的堆栈函数来绕过这个问题。 如果需要,此链接也可以提供帮助:


您可以使用;使用叶节点的
right
链接指向遍历中的下一个节点,如

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

叶节点
C
显式指向
D
,这是前序遍历中的下一个节点,
D
显式指向
E
。这使得插入和删除有点痛苦,但它提供了一个简单的前序遍历,无需递归和辅助堆栈

使用本地动态堆栈。