leetcode[103]:Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]
/**
 * 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) {

    int i, j;

    i=j=1;

    if(!root) return 0;
    if(root->left) i += maxDepth(root->left);
    if(root->right) j += maxDepth(root->right);

    if( i > j ) return i;

    return j;

}

int** zigzagLevelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {
    int res[100][100];
    int size[100];
    struct TreeNode stack[10000];
    int i,ress,j,k,l;
    int **result;

    l=maxDepth(root);

    if(!root) return NULL;
    result= (int**)malloc(sizeof(int*)*l);
    *columnSizes = (int*)malloc(sizeof(int*)*l);
    *returnSize = l;
    i=j=k=0;
    stack[0] = *root;
    size[0]=1;
    l=1;
    ress=1;
    while(l!=0)
    {
        l=0;
        result[i] = (int*)malloc(sizeof(int*)*size[i]);

        for(j=0;j<size[i];j++)
        {
            if(i%2==1)//只是这里不同
                result[i][size[i]-j-1]=stack[k+j].val;
            else result[i][j]=stack[k+j].val;
            if(stack[k+j].left) {l++;stack[ress++]=*stack[k+j].left; }
            if(stack[k+j].right) {l++;stack[ress++]=*stack[k+j].right;}
        }
        k += j;
        (*columnSizes)[i]=size[i];
        size[++i]=l;
    }
     return result;
}

和层序遍历利那题一样,奇数层反方向存储即可。
层序遍历:leetcode[102]:Binary Tree Level Order Traversal
解题:solution

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值