C语言----实现二叉树先序,中序和后序遍历

 就是正常的二叉树遍历,写代码的时候注意二维数组的操作

/**
 * 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;
}

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ftzchina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值