MOOC 3.2 binary tree traversal and storage structure

// 二叉树的存储结构

typedef struct TreeNode *BinTree;
typedef BinTree Position;
struct TreeNode
{
	ElementType Data;
	BinTree Left;
	BinTree Right;
};

void PreOrderTraversal(BinTree BT)
{
	if(BT) {
		printf("%d", BT->Data);
		PreOrderTraversal(BT->Left);
		PreOrderTraversal(BT->Right);
	}
}

void InOrderTraversal(BinTree BT)
{
	if(BT) {
		InOrderTraversal(BT->Left);
		printf("%d", BT->Data);
		InOrderTraversal(BT->Right);
	}
}

void PostOrderTraversal(BinTree BT)
{
	if(BT) {
		InOrderTraversal (BT-> Left); 
		InOrderTraversal (BT-> Right); 
		the printf ( "% D", BT-> the Data); 
	} 
} 

// nonrecursive inorder traversal algorithm (left and right root) 
// encounters a node, put it onto the stack, and to traverse its left subtree 
// when the left end of the sub-tree traversal, from the top of the stack and pop this node to access it 
// then its right pointer again to traverse the right of the node subtree 
void InOrderTraversal (BinTree the BT) 
{ 
	BinTree T = the BT; 
	stack CreateStack S = (the MaxSize); // create and initialize stack S 
	the while {(T || the IsEmpty (S)!) 
		the while (T) { 
			the Push (S, T); 
			T = T-> Left; 
		} 
		IF) {(the IsEmpty (S!) 
			T = Pop (S); 
			the printf ( "% 5D", T-> the Data); 
			T = T-> Right; 
		} 
	} 
} 

// traversal sequence 
/ * queue implementation: traversal starting from the root, the root node into the first team, then
Start execution cycle: dequeued node, the access node, the left and right son enqueue * / 
/ * 
	1. Remove the element from the queue 
	2. Access node to the node indicated
	3. If the node referring to an element point around the child node is not null, 
	the left and right child pointers enqueue order 
* / 
void LevelOrderTraversal (BinTree the BT) 
{ 
	Queue Q; 
	BinTree T; 
	IF (the BT!) Return; / / if empty tree directly returns 
	Q = CreateQueue (MaxSize); // create and initialize the queue Q 
	the addq (Q, the BT); 
	(! IsEmptyQ (Q)) the while 
	{ 
		T = the deleteq (Q); 
		the printf ( "% D \ n ", T-> Data); // remove access node queue 
		IF (T-> Left) the addq (Q, T-> Left); 
		IF (T-> Right) the addq (Q, T-> Right) ; 
	} 
}

  

Guess you like

Origin www.cnblogs.com/mjn1/p/11460643.html