非递归中序遍历二叉树-代码实例讲解

本文介绍了一种使用栈实现的二叉树中序遍历的非递归方法,并给出了详细的步骤说明与完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  中序遍历递归方法:

将root作为参数传入前序遍历函数,然后

  1. 调用中序遍历函数,以root的左子树作为参数传入;
  2. 显示数据(比如前序遍历树输出树里的数据)
  3. 调用中序遍历函数,以root的右子树作为参数传入;
  而在非递归调用中序遍历二叉树中,利用栈的LIFO的特点。因为中序遍历从二叉树最左的节点开始遍历,然后其父节点,最后父节点的右子树。因此算法为:
1.1.初始化当前指针cur指向root,利用循环将其移动到二叉树的最左下节点,直到指向NULL,在移动途中将访问的所有节点存入初始化栈中;
1.2 当当前指针cur指向NULL时,将存储在栈顶的指针赋予cur,然后输出cur指向节点的数据,然后将栈顶的内容出栈,最后再将cur指向其右子树;
 2    一直循环1.1与1.2直到栈为空。

  实际代码:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <stack>

using namespace std;

//Construct the node of the tree
struct treeNode{
    int data;
    struct treeNode *left;
    struct treeNode *right;
};

//Function to build your tree
//Return type: the pointer point to the treeNode
struct treeNode* newNode(int data){
    struct treeNode *node= new struct treeNode;
    node->data=data;
    node->left=NULL;
    node->right=NULL;
    return node;
}

void iterativeInorder(treeNode *root){
    bool done;
    treeNode* cur;
    //初始化:当前指针cur
    cur=root;
    done=false;
    
    //当二叉树为空时,直接return,不进行操作
    if (root==NULL) {
        return;
    }
    //当二叉树不为空时
    else{
        stack<struct treeNode*> s;
        while (!done) {
            //将cur的位置一直移动到树的最左下角,直到指向null,在移动过程中将所有访问的节点指针存入栈中
            if (cur!=NULL) {
                s.push(cur);
                cur=cur->left;
            }
            else{
                //当栈非空
                if (!s.empty()) {
                    cur=s.top();
                    cout<<cur->data<<" ";
                    s.pop();
                    
                    //the cur still points to what it pointed to
                    cur=cur->right;
                }
                //当栈为空,遍历完成,结束循环
                else{
                    done=true;
                }
            }
        }
    }
}

int main(){
    struct treeNode *root=newNode(9);
    root->left=newNode(8);
    root->right=newNode(3);
    root->left->left=newNode(2);
    root->left->right=newNode(1);
    root->right->left=newNode(5);
    root->right->right=newNode(7);
    iterativeInorder(root);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值