【leetcode】102. 二叉树的层序遍历

 

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector <vector <int>> ret;
        if (!root) {
            return ret;
        }

        queue <TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int currentLevelSize = q.size();
            ret.push_back(vector <int> ());
            for (int i = 1; i <= currentLevelSize; ++i) {
                auto node = q.front(); q.pop();
                ret.back().push_back(node->val);
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
        }
        
        return ret;
    }
};

 

void recurseion(struct TreeNode* root, int* returnSize, int* col, int cnt,int** arr){
    if (!root)
        return;
    if (cnt+1 > *returnSize)
        *returnSize = cnt+1;
    if (col[cnt] == 0)
        arr[cnt] = (int*)calloc(1000, sizeof(int*));
    arr[cnt][col[cnt]++] = root->val;
    recurseion(root->left, returnSize, col, cnt+1, arr);
    recurseion(root->right, returnSize, col, cnt+1, arr);
}
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    int** arr = (int**)calloc(1000, sizeof(int*));
    *returnSize = 0;
    *returnColumnSizes = (int*)calloc(1000, sizeof(int));
    recurseion(root, returnSize, *returnColumnSizes, 0, arr);
    return arr;
}

 

上一篇:leetcode-238-OK


下一篇:【leetcode】48. 全排列 2