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

/**
 * 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().
 */
#define NODE_SIZE 10000
int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    if(root==NULL) {
        *returnSize = 0;
        return NULL;
    }
    int** zzlOrder = (int**)malloc(sizeof(int*)*NODE_SIZE);
    int row = 0;
    int col = 0;
    *returnColumnSizes = (int*)malloc(sizeof(int)*NODE_SIZE);
    struct TreeNode* stk1[NODE_SIZE];
    struct TreeNode* stk2[NODE_SIZE];
    struct TreeNode* pNode = NULL;
    int top1 = -1;
    int top2 = -1;
    stk1[++top1] = root;
    
    while (top1!=-1 || top2!=-1) {
        
        zzlOrder[row] = (int* )malloc(sizeof(int)*NODE_SIZE);
        while(top1!=-1){
            pNode = stk1[top1--];
            zzlOrder[row][col++] = pNode->val;
            if(pNode->left!=NULL) stk2[++top2] = pNode->left;
            if(pNode->right!=NULL) stk2[++top2] = pNode->right;
        }
        (*returnColumnSizes)[row++] = col;
        col=0;
        if(top2==-1) break;

        zzlOrder[row] = (int* )malloc(sizeof(int)*NODE_SIZE);
        while(top2!=-1){
            pNode = stk2[top2--];
            zzlOrder[row][col++] = pNode->val;
            if(pNode->right!=NULL) stk1[++top1] = pNode->right;
            if(pNode->left!=NULL) stk1[++top1] = pNode->left;
        }
        (*returnColumnSizes)[row++] = col;
        col=0;
    }
    *returnSize = row;
    return zzlOrder;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值