二叉树非递归遍历

昨天做的题目里面,需要用到非递归的方法遍历二叉树。觉得这个东西,在思路上还不是特别清晰,所以,今天做下总结。



//总结下对树进行遍历的各种方法,包括前序、中序、后序的非递归方法。
#include <iostream>
#include <stack>

using namespace std;

struct TreeNode 
{
	int value;
	TreeNode *pLeft;
	TreeNode *pRight;
};

void addTreeNode(TreeNode *&pRoot,int *index,int &iCurrent){
	if(-1 != index[iCurrent]){
		TreeNode *pCurrent = new TreeNode;
		pCurrent->value = index[iCurrent++];
		pCurrent->pLeft = NULL;
		pCurrent->pRight = NULL;
		pRoot = pCurrent;

		addTreeNode(pRoot->pLeft,index,iCurrent);
		addTreeNode(pRoot->pRight,index,iCurrent);
	}else{
		++iCurrent;
	}
}

void createTree(TreeNode *&pRoot,int *index){
	int iCurrent = 0;
	addTreeNode(pRoot,index,iCurrent);
}

void preOrder(TreeNode *pRoot){
	stack<TreeNode*> s;
	cout << "先序:";
	while(!s.empty()||NULL != pRoot){
		if(NULL != pRoot){
			cout << pRoot->value << " ";
			s.push(pRoot);
			pRoot = pRoot->pLeft;
		}else{
			TreeNode *pCurrent = s.top();
			s.pop();
			pRoot = pCurrent->pRight;
		}
	}
	cout << endl;
}

void inOrder(TreeNode *pRoot){
	stack<TreeNode*> s;
	cout << "中序:";
	while(!s.empty()||NULL != pRoot){
		if(NULL != pRoot){
			s.push(pRoot);
			pRoot = pRoot->pLeft;
		}else{
			TreeNode *pCurrent = s.top();
			s.pop();
			cout << pCurrent->value << " ";
			pRoot = pCurrent->pRight;
		}
	}
	cout << endl;
}

void postOrder(TreeNode *pRoot){
	stack<TreeNode*> s;
	TreeNode *pre = NULL;
	cout << "后序:";
	while(!s.empty()||NULL != pRoot){
		if(NULL != pRoot){
			s.push(pRoot);
			pRoot = pRoot->pLeft;
		}else{
			TreeNode *pCurrent = s.top();
			if(NULL == pCurrent->pRight || pre == pCurrent->pRight){
				cout << pCurrent->value << " ";
				pre = pCurrent;
				s.pop();
				pRoot = NULL;
			}else{
				pRoot = pCurrent->pRight;
			}
		}
	}
	cout << endl;
}

int main(){
	int index[] = {8,6,5,-1,-1,-1,10,11,-1,-1,-1};//测试数据
	TreeNode *pRoot = NULL;

	createTree(pRoot,index);//创建树
/*
         8
        / \
       6   10
      /    /
     5    11
*/
	preOrder(pRoot);
	inOrder(pRoot);
	postOrder(pRoot);

	return 1;
}


你可能感兴趣的:(二叉树非递归遍历)