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