题干朴实无华的分别要求返回二叉树的先序,中序和后序遍历,思路很简单就是先序遍历一遍,中序遍历一遍,后序遍历一遍,然后存起来,返回,就可以了,但是因为我们要用C语言,所以就有很多需要注意到的地方了
上代码
/*
基本思路:
*/
/*计算二叉树大小*/
void getTreeSize(struct TreeNode* root,int* count)
{
/*求二叉树的节点个数就是左子树,右子树,根的个数总和*/
++(*count);//根
/*右子树*/
if(root->right){
getTreeSize(root->right,count);
}
/*左子树*/
if(root->left){
getTreeSize(root->left,count);
}
}
/*前序遍历二叉树 中-左-右*/
void preTreeOrders(struct TreeNode* root, int* nodes, int* count){
/*中*/
nodes[(*count)++] = root -> val;//将每一个根值都存入nodes中,然后向后移动一格
/*左*/
if(root -> left)
preTreeOrders(root -> left, nodes, count);
/*右*/
if(root -> right)
preTreeOrders(root -> right, nodes, count);
}
/*中序遍历二叉树 左-中-右*/
void midTreeOrders(struct TreeNode* root, int* nodes, int* count)
{
//左
if(root -> left)
midTreeOrders(root -> left, nodes, count);
//中
nodes[(*count)++] = root -> val;
//右
if(root -> right)
midTreeOrders(root -> right, nodes, count);
}
/*后序遍历二叉树 左-右-中*/
void postTreeOrders(struct TreeNode* root, int* nodes, int* count)
{
//左
if(root -> left)
postTreeOrders(root -> left, nodes, count);
//右
if(root -> right)
postTreeOrders(root -> right, nodes, count);
//中
nodes[(*count)++] = root -> val;
}
int** threeOrders(struct TreeNode* root, int* returnSize, int** returnColumnSizes ) {
// write code here
int** ppResult = NULL;//定义一个ppResult用来存放二叉树的前序,中序,后序遍历
int treeSize = 0;//定义一个treeSize来存放二叉树的节点个数
getTreeSize(root,&treeSize);//定义一个函数来求出二叉树的节点个数
if(treeSize){/*这个条件判断的意思是如果二叉树不为0就继续执行*/
*returnSize = 3; //这个是固定的,前序,中序,后序总共三个
ppResult = (int**)malloc(sizeof(int*)*3);//给ppResult开辟空间用来存放二叉树的前序,中序,后序遍历
/*开始前序遍历*/
int index = 0;//标记符号
int* preTree = (int*)malloc(sizeof(int)*treeSize);//给前序遍历开辟空间
preTreeOrders(root,preTree,&index);//前序遍历
ppResult[0] = preTree;//将前序遍历的结果(也就是前序遍历中的nodes的值)存入ppResult[0]
/*开始中序遍历*/
index = 0;//每次开始之前标记清零,标记的作用就是用来记录,遍历了总共多少个节点(或者说起到一个向后移动的格子的作用)
int* midTree = (int*)malloc(sizeof(int)*treeSize);//给中序遍历开辟空间
midTreeOrders(root,midTree,&index);//中序遍历
ppResult[1] = midTree;//将中序遍历的结果(也就是中序遍历中的nodes的值)存入ppResult[1]
/*开始后序遍历*/
index = 0;//每次开始之前标记清零,标记的作用就是用来记录,遍历了总共多少个节点(或者说起到一个向后移动的格子的作用)
int* postTree = (int*)malloc(sizeof(int)*treeSize);//给后序遍历开辟空间
postTreeOrders(root,postTree,&index);//后序遍历
ppResult[2] = postTree;//将后序遍历的结果(也就是后序遍历中的nodes的值)存入ppResult[2]
int* columns = (int*)malloc(sizeof(int) * 3);//开辟空间
columns[0] = columns[1] = columns[2] = treeSize;//返回有多少列,C语言的限制罢了
*returnColumnSizes = columns;//返回。固定的
}
return ppResult;//最后返回
}