102

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

例如:
给定二叉树: [3,9,20,null,null,15,7]
在这里插入图片描述
返回其层次遍历结果:
在这里插入图片描述
C++,应该是最短的代码了。

层序遍历一般来说确实是用队列实现的,但是这里很明显用递归前序遍历就能实现呀,而且复杂度O(n)。。。

要点有几个:

利用depth变量记录当前在第几层(从0开始),进入下层时depth + 1;
如果depth >= vector.size()说明这一层还没来过,这是第一次来,所以得扩容咯;
因为是前序遍历,中-左-右,对于每一层来说,左边的肯定比右边先被遍历到,实际上后序中序都是一样的。。。
代码如下:

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        pre(root, 0, ans);
        return ans;
    }
    
    void pre(TreeNode *root, int depth, vector<vector<int>> &ans) {
        if (!root) return ;
        if (depth >= ans.size())
            ans.push_back(vector<int> {});
        ans[depth].push_back(root->val);
        pre(root->left, depth + 1, ans);
        pre(root->right, depth + 1, ans);
    }
};

C语言也是构造二维数组进行存储:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int getdepth(struct TreeNode *root){
    if(root == NULL) return 0;
    int l = getdepth(root->left), r = getdepth(root->right);
    return (l > r ? l : r) + 1;
}

void getcnt(struct TreeNode *root, int k, int *cnt){
    if(root == NULL) return;
    cnt[k] += 1;
    getcnt(root->left, k + 1, cnt);
    getcnt(root->right, k + 1, cnt);
    return;
}

void getresult(struct TreeNode *root, int k,int *cnt, int **ret){
    if(root == NULL) return;
    ret[k][cnt[k]++] = root->val;
    getresult(root->left, k + 1, cnt, ret);
    getresult(root->right, k + 1, cnt, ret);
}
/**
 * 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** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    int depth = getdepth(root);
    int **ret = (int **)malloc(sizeof(int *) * depth);
    int *cnt = (int *)calloc(depth, sizeof(int));
    getcnt(root, 0, cnt);
   // cnt[0] = 1, cnt[1] = 2, cnt[3] = 2;
   for(int i  = 0; i < depth; i++){
       ret[i] = (int *)malloc(sizeof(int) * cnt[i]);
       cnt[i] = 0;
   }
   getresult(root, 0, cnt ,ret);
   *returnSize = depth;
   *returnColumnSizes = cnt;
   return ret;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值