leetcode:二叉树层序遍历(C实现,递归与非递归)

1.递归法

int depth(struct TreeNode *root)
{
   
    int ld=0,rd=0;
    if(root)
	{
   
        ld=depth(root->left)+1;
        rd=depth(root->right)+1;  
    }
    return ld>=rd?ld:rd;
}

void level_order_recursion(struct TreeNode *root,int **array,int * ColumnSizes,int level)
{
   
    if(root == NULL)
        return;

    if(array[level] == NULL)
    {
   
       //array[level] = (int*)malloc(sizeof(int) * pow(2,level));不为何在最后一个调用时没有通过
        array[level] = (int*)malloc(sizeof(int) * 200);
    }
    array[level][ColumnSizes[level]++] = root->val;

    if(root->left)
    {
   
        level_order_recursion(root->left,array,ColumnSizes,level+1);
    }
    if(root->right)
    {
   
        level_order_recursion(root->right,array,ColumnSizes,level+1);
    }
}

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** levelOrderRecursion(struct TreeNode* root, int* returnSize, 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值