二叉树的遍历(前序、中序、后序)

struct TreeNode
{
	int val;
	TreeNode*  leftchild;
	TreeNode*  rightchild;
	TreeNode(int x) : val(x), leftchild(NULL), rightchild(NULL) {}
};


void PreOrder(TreeNode *root)  //前序遍历
{
	if (root == NULL)
	{
		return;
	}
	cout << root->val<< " ";
	PreOrder(root->leftchild);
	PreOrder(root->rightchild);
}



void InOrder(TreeNode *root)  //中序遍历
{
	if (root == NULL)
	{
		return;
	}
	
	InOrder(root->leftchild);
	cout << root->val << " ";
	InOrder(root->rightchild);
}

void PastOrder(TreeNode * root)  //后序遍历
{
	if (root == NULL)
	{
		return;
	}
	PastOrder(root->leftchild);
	PastOrder(root->rightchild);
	cout << root->val << " ";
}

 

你可能感兴趣的:(算法)