二叉树的锯齿形层次遍历
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
其实就是用两个栈,存储的时候用一个栈,遍历的时候倒进另一个栈。
当时的写法我真是佩服自己。。
//当时的废话
二叉树层次遍历的升级版,我的思路是把队列和栈结合起来,存储的时候用队列,遍历的时候用栈。
主要难点在于存储的时候存储顺序,从左往右遍历的时候按先左后右的顺序存节点,从右往左遍历的时候,按先右后左的顺序存节点。
然后就是千万不要在头脑昏昏沉沉地时候做题,基本大部分时间都浪费在了改BUG上,这里写错,那里写漏。。。我现在好痛苦,我要死了。
如果把if(order)放进while(count--)里的话,代码会更短,但是耗时会久一点。
/** * 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 lDepth=maxDepth(root->left)+1; int rDepth=maxDepth(root->right)+1; return lDepth>rDepth?lDepth:rDepth; } int** zigzagLevelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) { if(!root) return NULL; struct TreeNode **queue=(struct TreeNode **)malloc(sizeof(struct TreeNode *)*10000); struct TreeNode *p; int depth=maxDepth(root); int **a=(int **)malloc(sizeof(int *)*depth); *columnSizes=(int *)malloc(sizeof(int)*depth); int i; for(i=0;i<depth;i++) (*columnSizes)[i]=0; int front=-1,rear=-1,top; int count,layer=0; bool order=true; queue[++rear]=root; while(front<rear) { count=rear-front; a[layer]=(int *)malloc(sizeof(int)*count); top=rear; front=rear; if(order) { while(count--) { p=queue[top--]; if(p->left) queue[++rear]=p->left; if(p->right) queue[++rear]=p->right; a[layer][(*columnSizes)[layer]]=p->val; (*columnSizes)[layer]++; } } else { while(count--) { p=queue[top--]; if(p->right) queue[++rear]=p->right; if(p->left) queue[++rear]=p->left; a[layer][(*columnSizes)[layer]]=p->val; (*columnSizes)[layer]++; } } order=!order; layer++; } *returnSize=depth; return a; }