树的前序遍历,中序遍历,后序遍历,层次(广度)遍历

//树的前序遍历
void BTPreorder(pTree root){
	stack <treeT *> s;
	while(root!=null||!s.empty()){
		if(root!=null){
			visit(root);
			s.push(root);
			root=root->next;
		}
		else{
			root=s.top();
			s.pop();//根出栈,因为已经访问了根节点
			root=root->right;
		}
	}
}


//树的中序遍历
void BTInorder(pTree root){
	stack <treeT *>s;
	while(root!=null||!s.empty()){
		if(root!=null){
			s.push(root);
			root=root->left;
		}
		else{
			root=s.top();
			visit(root);
			s.pop();
			root=root->right;
		}
	}
}

//树的后序遍历
void BTPostorder(pTree root){
	stack <treeT *>s;
	pTree pre=null;
	pTree top=null;
	while(root!=null||!s.empty()){
		if(root!=null){
			s.push(root);
			root=root->left;
		}
		else{
			top=s.top();
			if(top->right!=null&&top->right!=pre)
				root=root->right;
			else{
				visit(top);
				pre=top;
				s.pop();
			}
		}
	}
}

//树的层次遍历(广度)
void BTLevelorder(pTree root){
	queue <tree *>q;
	treeT *treePtr;
	q.push(root);
	while(!q.empty()){
		treePtr=q.front();
		q.pop();
		visist(treePtr);
		if(treePtr->left!=null)
			q.push(treePtr->left);
	    if(treePtr->right!=null)
			q.push(treePtr->right);
	}
}


你可能感兴趣的:(树的前序遍历,中序遍历,后序遍历,层次(广度)遍历)