leetcode[102]:Binary Tree Level Order Traversal

来源:互联网 发布:礼券提货系统源码 php 编辑:程序博客网 时间:2024/05/29 09:13

Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

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

3
/ \
9 20
/ \
15 7

return its level order traversal as:
[
[3],
[9,20],
[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** levelOrder(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++)        {            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;}

层序遍历,压栈。主要问题是双重指针初始化,malloc,引用等问题。

0 0
原创粉丝点击