首页 > 代码库 > 二叉树的遍历算法

二叉树的遍历算法

二叉树的先序、中序、后序以及层次遍历算法

非递归版本:

vector<int> postorderTraversal(TreeNode *root){	vector<int> vect;	if (!root)	{		return vect;	}	stack<TreeNode*> stackData;	stackData.push(root);	TreeNode* cur = NULL;	TreeNode* pre = NULL;	while (!stackData.empty())	{		cur=stackData.top();		if (cur->left==NULL&&cur->right==NULL || (pre!=NULL)&&(pre==cur->left||pre==cur->right))		{			vect.push_back(cur->val);			pre=cur;			stackData.pop();		}else{			if (cur->right)			{				stackData.push(cur->right);			}			if (cur->left)			{				stackData.push(cur->left);			}		}	}	return vect;}vector<int> preordertTraversal(TreeNode *root){		vector<int> vect;		if (!root)	{		return vect;	}	stack<TreeNode*> stackData;	TreeNode *pNode = root;	while (pNode||!stackData.empty())	{		while (pNode)		{			vect.push_back(pNode->val);			stackData.push(pNode);			pNode=pNode->left;		}		if (!stackData.empty())		{			pNode=stackData.top();			stackData.pop();			pNode=pNode->right;		}	}	return vect;}vector<int> inorderTraversal(TreeNode *root){	vector<int> inorder;	stack<TreeNode*> stackData;	TreeNode *pNode=root;	while(pNode||!stackData.empty()){		while(pNode){			stackData.push(pNode);			pNode=pNode->left;		}		if(!stackData.empty()){			pNode=stackData.top();			inorder.push_back(pNode->val);			stackData.pop();			pNode = pNode->right;		}	}	return inorder;}vector<vector<int> > levelOrderBottom(TreeNode *root){	vector<vector<int> > result;	if (!root)	{		return result;	}	vector<int> curlevel;	queue<TreeNode*> q;	q.push(root);	q.push(NULL);	while (!q.empty())	{		TreeNode * node = q.front();		q.pop();		if(node)		{			curlevel.push_back(node->val);			if (node->left)			{				q.push(node->left);			}			if (node->right)			{				q.push(node->right);			}		}else {			result.push_back(curlevel);			curlevel.clear();			if(!q.empty())  //该处相当关键 否则会出现死循环				q.push(NULL);		}	}	reverse(result.begin(),result.end());	return result;  }

  

二叉树的遍历算法