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

  前序遍历树递归调用并不算难,将root作为参数传入前序遍历函数,然后

  1. 显示数据(比如前序遍历树输出树里的数据);
  2. 调用前序遍历函数,以root的左子树作为参数传入;
  3. 调用前序遍历函数,以root的右子树作为参数传入;
  而如果要求用非递归调用前序遍历树,就需要引入stack-栈(请与 heap-堆区分开来)的运用,其实在递归调用算法中,stack也是存在的,只是是没有直接申明,递归的数据都会暂时存在stack中,正因为这样当树中数据过多,存在多次递归调用,这样就会存在堆溢出的可能性,这也是为什么我们需要知道非递归调用前序遍历树的一个原因。

  前序遍历树非递归算法:
1. 创建一个空stack, 将root push到stack中

2. 当stack不为空时做:
a). 输出位于stack顶端,树的数据;然后pop掉位于stack顶端的内容;
b). 将刚pop掉内容的右子树push进stack;
c). 将刚pop掉内容的左子树push进stack;
注意:右子树先放入stack, 为了先输出左子树内容(FIFO)

  具体代码实现:
#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 iterativePreorder(treeNode *root){
    if (root==NULL) {
        return;
    }
    else{
        //Create stack, form of item is pointer to treeNode
        stack<struct treeNode*> s;
        s.push(root);
        
        //While stack is not empty, do following
        while (s.empty()==false) {
            struct treeNode *node=s.top();
            cout<<node->data<<" ";
            s.pop();
            
            //Push right child of popped item to stack
            //Use if to make sure
            if (node->right) {
                s.push(node->right);
            }
            if (node->left) {
                s.push(node->left);
            }
        }
    }
}

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);
    iterativePreorder(root);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值