leetcode 103-二叉树的锯齿形层序遍历

给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]


示例 2:

输入:root = [1]
输出:[[1]]


示例 3:

输入:root = []
输出:[]

提示:

树中节点数目在范围 [0, 2000] 内
-100 <= Node.val <= 100

 思路:

层次遍历该树,将节点按层次保留下来,然后将层数为奇数的节点值的倒序一下

/**
 * 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 *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
//可以选择层次遍历后,将奇数层的数据反转即可
int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    *returnSize = 0;
     if(root == NULL)
        return NULL;

    *returnColumnSizes = malloc(sizeof(int) * 2000);
    int** res = (int**)malloc(sizeof(int*) * 2000);
   
    struct TreeNode *arr[2000];
    arr[0] = root;
    int head = 0, tail  = 1, last;
    //层次遍历并将节点的值记录下来
    while(head != tail){
        last = tail;
        int col_size = 0;
        res[*returnSize] = malloc(sizeof(int) * (tail - head));
        while(head < last){
            res[*returnSize][col_size++] = arr[head]->val;
            if(arr[head]->left)
                arr[tail++] = arr[head]->left;
            if(arr[head]->right)
                 arr[tail++] = arr[head]->right;
            head++;
        }
        (*returnColumnSizes)[*returnSize] = col_size;
        (*returnSize)++;
    }
    //将层数为奇数的节点值倒序
    for(int i = 0; i < *returnSize ;i++){
        if(i % 2 == 1){
            for(int j = 0; j < (*returnColumnSizes)[i] / 2; j++){
                    last = res[i][j];
                    res[i][j] = res[i][(*returnColumnSizes)[i] - j - 1];
                    res[i][(*returnColumnSizes)[i] - j - 1] = last;
            }
        }
    }
    return res;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值