前序遍历树递归调用并不算难,将root作为参数传入前序遍历函数,然后
- 显示数据(比如前序遍历树输出树里的数据);
- 调用前序遍历函数,以root的左子树作为参数传入;
- 调用前序遍历函数,以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;
}