就是正常的二叉树遍历,写代码的时候注意二维数组的操作
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
* @return int* returnSize 返回数组行数
* @return int** returnColumnSizes 返回数组列数
*/
#define ROWS 3
int getTreeNodeNum(struct TreeNode *root)
{
if(root)
{
return getTreeNodeNum(root->left) + getTreeNodeNum(root->right) + 1;
}
return 0;
}
void front(struct TreeNode *root,int *output,int *index)
{
if(root)
{
output[*index] = root->val;
(*index)++;
front(root->left,output,index);
front(root->right,output,index);
}
}
void middle(struct TreeNode *root,int *output,int *index)
{
if(root)
{
middle(root->left,output,index);
output[*index] = root->val;
(*index)++;
middle(root->right,output,index);
}
}
void back(struct TreeNode *root,int *output,int *index)
{
if(root)
{
back(root->left,output,index);
back(root->right,output,index);
output[*index] = root->val;
(*index)++;
}
}
int** threeOrders(struct TreeNode* root, int* returnSize, int** returnColumnSizes )
{
// write code here
if(root == NULL)
return NULL;
int i = 0;
int index = 0;
int treeNodeNum = getTreeNodeNum(root);
int **output = (int **)malloc(ROWS*sizeof(int*));
int *columes = (int *)malloc(ROWS*sizeof(int*));
*returnSize = ROWS;
*returnColumnSizes = columes;
for(i=0;i<ROWS;i++)
{
output[i] = (int*)malloc(treeNodeNum*sizeof(int*));
columes[i] = treeNodeNum;
}
index = 0;
front(root,*output,&index);
index = 0;
middle(root,*(output+1),&index);
index = 0;
back(root,*(output+2),&index);
return output;
}