LeetCode题解(三)

LeetCode题解(三)

Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

void merge(int* nums1, int m, int* nums2, int n) {
    int k = m + n - 1;
    m -= 1;
    n -= 1;
    while (k >= 0) {
        if (n < 0 || (m >= 0 && nums1[m] > nums2[n]))
            nums1[k--] = nums1[m--];
        else
            nums1[k--] = nums2[n--];
    }
}

Same Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if (!p && !q)
        return true;
    if (!p || !q)
        return false;
    return p->val == q->val && isSameTree(p->left, q->left) &&
        isSameTree(p->right, q->right);
}

Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.

confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as “{1,2,3,#,#,4,#,#,5}”.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

 static bool is_sym(struct TreeNode* left, struct TreeNode* right) {
    if (!left && !right)
        return true;
    if (!left || !right)
        return false;
    if (left->val != right->val)
        return false;

    if(!is_sym(left->left, right->right))
        return false;
    if (!is_sym(left->right, right->left))
        return false;

    return true;
}

bool isSymmetric(struct TreeNode* root) {
    if (!root)
        return true;
    return is_sym(root->left, root->right);
}

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]
]
confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as “{1,2,3,#,#,4,#,#,5}”.

#define ELE_NUM 10000

typedef struct Ele {
    int val;
    int level;
} Ele;

typedef struct TreeNode TreeNode;

static void tree2arr(TreeNode* node, Ele* ele, int level,
                     int* global_index, int* total_level, int* col_size) {
    if (!node)
        return;
    (ele + *global_index)->val = node->val;
    (ele + *global_index)->level = level;
    ++(*global_index);
    ++(*(col_size + level));
    if (level > *total_level)
        *total_level = level;
    tree2arr(node->left, ele, level + 1, global_index, total_level, col_size);
    tree2arr(node->right, ele, level + 1, global_index, total_level, col_size);
}

/**
 * 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** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {
    *returnSize = 0;
    if (!root) {
        *columnSizes = NULL;
        return NULL;
    }

    Ele* ele = (Ele*)malloc(sizeof(Ele) * ELE_NUM);
    memset(ele, 0xff, sizeof(Ele) * ELE_NUM);
    int col_size[ELE_NUM];
    memset(col_size, 0, sizeof(int) * ELE_NUM);
    int level = 0;
    int global_index = 0;
    int total_level = 0;

    // 遍历一遍树,得到每个结点的值以及所在的层数
    tree2arr(root, ele, level, &global_index, &total_level, col_size);
    total_level += 1;

    int** result = (int**)malloc(sizeof(int*) * total_level);
    *columnSizes = (int*)malloc(sizeof(int) * total_level);
    for (int i = 0; i < total_level; ++i) {
        *(result + i) = (int*)malloc(sizeof(int) * col_size[i]);
        *(*columnSizes + i) = 0;
    }

    for (int i = 0; i < global_index; ++i) {
        level = (ele + i)->level;
        *(*(result + level) + *(*columnSizes + level)) = (ele + i)->val;
        *(*columnSizes + level) += 1;
    }
    *returnSize = total_level;

    free(ele);

    return result;
}

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

static void max_depth(struct TreeNode* node, int level, int* depth) {
    if (!node)
        return;

    if (level > *depth)
        *depth = level;

    max_depth(node->left, level + 1, depth);
    max_depth(node->right, level + 1, depth);
}


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxDepth(struct TreeNode* root) {
    int depth = 0;
    max_depth(root, 1, &depth);
    return depth;
}

Binary Tree Level Order Traversal II

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

For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]

求测试,以下代码本地测试通过,但是LeetCode运行时错误。上面此题的正序代码可能也隐藏有BUG。
标记:先放在这了,以后再找BUG。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

#define ELE_NUM 10000

typedef struct Ele {
    int val;
    int level;
} Ele;

typedef struct TreeNode TreeNode;

static void tree2arr(TreeNode* node, Ele* ele, int level,
                     int* global_index, int* total_level, int* col_size) {
    if (!node)
        return;
    (ele + *global_index)->val = node->val;
    (ele + *global_index)->level = level;
    ++(*global_index);
    ++(*(col_size + level));
    if (level > *total_level)
        *total_level = level;
    tree2arr(node->left, ele, level + 1, global_index, total_level, col_size);
    tree2arr(node->right, ele, level + 1, global_index, total_level, col_size);
}

/**
 * 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** levelOrderBottom(struct TreeNode* root, int** columnSizes, int* returnSize) {
    *returnSize = 0;
    if (!root) {
        *columnSizes = NULL;
        return NULL;
    }

    Ele* ele = (Ele*)malloc(sizeof(Ele) * ELE_NUM);
    memset(ele, 0xff, sizeof(Ele) * ELE_NUM);
    int col_size[ELE_NUM];
    memset(col_size, 0, sizeof(int) * ELE_NUM);
    int level = 0;
    int global_index = 0;
    int total_level = 0;

    // 遍历一遍树,得到每个结点的值以及所在的层数
    tree2arr(root, ele, level, &global_index, &total_level, col_size);
    total_level += 1;

    int** result = (int**)malloc(sizeof(int*) * total_level);
    *columnSizes = (int*)malloc(sizeof(int) * total_level);
    for (int i = 0; i < total_level; ++i) {
        *(result + i) = (int*)malloc(sizeof(int) * col_size[i]);
        *(*columnSizes + i) = 0;
    }

    for (int i = 0; i < global_index; ++i) {
        level = total_level - (ele+i)->level - 1;
        *(*(result + level) + *(*columnSizes + level)) = (ele + i)->val;
        *(*columnSizes + level) += 1;
    }
    *returnSize = total_level;

    free(ele);

    return result;
}

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

static int diff(struct TreeNode* node) {
    if (!node)
        return 0;
    int left_height = diff(node->left);
    if (left_height == -1)
        return -1;
    int right_height = diff(node->right);
    if (right_height == -1)
        return -1;

    int d = left_height > right_height ? left_height - right_height : right_height - left_height;
    if (d > 1)
        return -1;
    else
        return d = (left_height > right_height) ? left_height + 1 : right_height + 1;
}


bool isBalanced(struct TreeNode* root) {
    if (!root)
        return true;
    int d = diff(root);
    if (d == -1)
        return false;
    else
        return true;
}

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int minDepth(struct TreeNode* root) {
    if (!root)
        return 0;

    int left_height = minDepth(root->left);
    int right_height = minDepth(root->right);
    if (!left_height && !right_height)
        return 1;

    if (!left_height)
        left_height = INT_MAX;
    if (!right_height)
        right_height = INT_MAX;

    return left_height < right_height ? left_height + 1 : right_height + 1;
}

Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

static bool path_sum(struct TreeNode* node, int sub_sum, int sum) {
    if (!node)
        return false;

    sub_sum += node->val;
    if (!node->left && !node->right) {
        if (sub_sum == sum)
            return true;
        else 
            return false;
    } else {
        return path_sum(node->left, sub_sum, sum) || 
            path_sum(node->right, sub_sum, sum);
    }
}

bool hasPathSum(struct TreeNode* root, int sum) {
    return path_sum(root, 0, sum);
}

Pascal’s Triangle

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

/**
 * Return an array of arrays.
 * 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** generate(int numRows, int** columnSizes) {
    if (!numRows) {
        *columnSizes = NULL;
        return NULL;
    }

    int** result = (int**)malloc(sizeof(int*) * numRows);
    *columnSizes = (int*)malloc(sizeof(int) * numRows);
    *result = (int*)malloc(sizeof(int));
    **result = 1; **columnSizes = 1;
    for (int i = 1; i < numRows; ++i) {
        *(*columnSizes + i) = 0;
        *(result + i) = (int*)malloc(sizeof(int) * (i + 1));
        for (int j = 0; j < i + 1; ++j) {
            if (j == 0 || j == i)
                *(*(result + i) + j) = 1;
            else
                *(*(result + i) + j) = *(*(result + i - 1) + j - 1) +
                    *(*(result + i - 1) +j);
            *(*columnSizes + i) += 1;
        }
    }

    return result;
}
posted @ 2016-05-25 18:03  corfox  阅读(246)  评论(0编辑  收藏  举报