【数据结构】二叉树的层序遍历

问题:给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

思路分析:

这道题的要求是返回遍历结果放在一个二维数组里面,所以我们可以开辟三个数组,第一个数组里面一开始放入第一层数据,放完之后,出数据时,出一个数据,就把该数据的左右子树带到第二个数组里面,当第一层数据出完时,再把第二个数组里面的数据放入第一个数组,重复以上操作,直至两个数组都为空时,遍历结束。

 

具体实现代码如下(因为该代码是直接在oj上面写的,所以没有测试部分的代码):

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

int maxDepth(struct TreeNode* root)
{
    if(root==NULL)
        return 0;
    int leftDepth=maxDepth(root->left);
    int rightDepth=maxDepth(root->right);
    return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}

int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {
    if(root==NULL)
        return NULL;
    int depth=maxDepth(root);
    int** levelArray=(int**)malloc(sizeof(int*)*depth);
    int maxLevelSize=1000;
    struct TreeNode** a1=(struct TreeNode**)malloc(sizeof(struct TreeNode*)*maxLevelSize);
    struct TreeNode** a2=(struct TreeNode**)malloc(sizeof(struct TreeNode*)*maxLevelSize);
    int a1Size=0;
    int a2Size=0;
    *returnSize=depth;
    *columnSizes=(int*)malloc(sizeof(int)*depth);
    if(root)
    {
        a1[0]=root;
        a1Size=1;
    }
    int level=0;//第0层
    while(level<depth)
    {
        levelArray[level]=malloc(sizeof(int)*a1Size);
        for(int i=0;i<a1Size;i++)
        {
            levelArray[level][i]=a1[i]->val;
        }
        (*columnSizes)[level]=a1Size;
        int k=0;
        for(int j=0;j<a1Size;j++)
        {
            if(a1[j]->left)
                a2[k++]=a1[j]->left;
            if(a1[j]->right)
                a2[k++]=a1[j]->right;
        }
        a2Size=k;
        struct TreeNode** a=a1;
        a1=a2;
        a2=a;
        
        a1Size=a2Size;
        a2Size=0;
        level++;
    }
    return levelArray;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值