LeetCode_107. 二叉树的层次遍历 II

题目

107. 二叉树的层次遍历 II

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7

返回其自底向上的层次遍历为:

[
[15,7],
[9,20],
[3]
]

题解

思路:详见102. 二叉树的层次遍历,改成从下向上去存结果就行了

/**
 * 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 get_depth(struct TreeNode *root) {
    if (root == NULL) {
        return 0;
    }
    int ldepth = get_depth(root->left) + 1;
    int rdepth = get_depth(root->right) + 1;
    rdepth > ldepth && (ldepth = rdepth);
    return ldepth;
}

void get_size(struct TreeNode *root, int *columnSizes, int level) {
    if (root == NULL) {
        return ;
    }
    ++columnSizes[level];
    get_size(root->left, columnSizes, level - 1);
    get_size(root->right, columnSizes, level - 1);

}

void get_val(struct TreeNode *root, int *columnSizes, int **data, int level) {
    if (root == NULL) {
        return ;
    }
    data[level][columnSizes[level]++] = root->val;
    get_val(root->left, columnSizes, data, level - 1);
    get_val(root->right, columnSizes, data, level - 1);
}

int** levelOrderBottom(struct TreeNode *root, int **columnSizes, int *returnSize) {
    *returnSize = get_depth(root);
    *columnSizes = (int *)calloc((*returnSize), sizeof(int));
    int **data = (int **)malloc(sizeof(int *) * (*returnSize)); 
    get_size(root, *columnSizes, *returnSize - 1);
    for (int i = 0; i < *returnSize; i++) {
        data[i] = (int *)malloc(sizeof(int ) * (*columnSizes)[i]);
        (*columnSizes)[i] = 0;
    }
    get_val(root, *columnSizes, data, *returnSize - 1);
    return data;
}

LeetCode练习汇总

你可能感兴趣的:(LeetCode,数据结构,c/c++,二叉树,递归)