其他分享
首页 > 其他分享> > 数据结构:二叉树前中后序遍历(递归)

数据结构:二叉树前中后序遍历(递归)

作者:互联网

二叉树遍历将其看做根,左子树,右子树三部分,其中前序遍历是根,左,右;中序为左、根、右;后序为左、右、根。
简单来说根的位置在哪就是什么序。

在这里插入图片描述
前序遍历:

ABDCEF

 struct TreeNode {
     int val;
     struct TreeNode *left;
     struct TreeNode *right;
 };
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int treeSize(struct TreeNode* root)
{
	if (root == NULL)
		return 0;
	else
		return treeSize(root->left) + treeSize(root->right) + 1;
}
int* _preorderTraversal(struct TreeNode* root, int* preorder, int* pindex)
{
	if (root == NULL)
	{
		return;
	}
	preorder[*pindex] = root->val;
	++(*pindex);
	_preorderTraversal(root->left, preorder, pindex);
	_preorderTraversal(root->right, preorder, pindex);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
	*returnSize = treeSize(root);
	int* preorder = (int*)malloc(sizeof(int)*(*returnSize));
	int index = 0;
	_preorderTraversal(root, preorder, &index);
	return preorder;
}

中序遍历

DBAECF

int treeSize(struct TreeNode* root)
{
	if (root == NULL)
		return 0;
	else
		return treeSize(root->left) + treeSize(root->right) + 1;
}
int* _inorderTraversal(struct TreeNode* root, int* inorder, int* pindex)
{
	if (root == NULL)
		return;
	_inorderTraversal(root->left, inorder, pindex);
	inorder[*pindex] = root->val;
	++(*pindex);
	_inorderTraversal(root->right, inorder, pindex);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
	*returnSize = treeSize(root);
	int* inorder = (int*)malloc(sizeof(int)*(*returnSize));
	int index = 0;
	_inorderTraversal(root, inorder, &index);
	return inorder;
}

后序遍历

DBEFCA

int treeSize(struct TreeNode* root)
{
	if (root == NULL)
		return 0;
	else
		return treeSize(root->left) + treeSize(root->right) + 1;
}
int* _posorderTraversal(struct TreeNode* root, int* posorder, int* pindex)
{
	if (root == NULL)
		return;
	_posorderTraversal(root->left, posorder, pindex);
	_posorderTraversal(root->right, posorder, pindex);
	posorder[*pindex] = root->val;
	++(*pindex);
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
	*returnSize = treeSize(root);
	int* posorder = (int*)malloc(sizeof(int)*(*returnSize));
	int index = 0;
	_posorderTraversal(root, posorder, &index);
	return posorder;
}

标签:遍历,TreeNode,struct,前中,treeSize,int,pindex,二叉树,root
来源: https://blog.csdn.net/Mmmmmmmrr/article/details/89927666