1. 程式人生 > >簡單的leetcode(一)

簡單的leetcode(一)

invert binary tree

Invert a binary tree.

  4
 /   \
2     7
/ \   / \
1   3 6   9

to

     4
    /   \
   7     2   
  / \   / \     
 9   6 3   1

Trivia: This problem was inspired by this original tweet by Max
Howell: Google: 90% of our engineers use the software you wrote
(Homebrew), but you can’t invert a binary tree on a whiteboard so fuck
off. Subscribe to see which companies asked this question

問題分析很簡單,其實就是一個深度優先遍歷的問題,它的一個子問題就是左孩子和右孩子已經完成交換,然後把左孩子和右孩子交換就好。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    if (root == NULL)
        return
; invertTree(root->left); invertTree(root->right); struct TreeNode *p = root->left; root->left = root->right; root->right = p; }

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.

Subscribe to see which companies asked this question

找出一個樹的最大深度。也是一個遞迴的問題,首先如果知道左子樹和右子樹的深度,那麼在選取一個最大的然後加一就行。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxDepth(struct TreeNode* root) {
    if (root == NULL) return 0;
    int dLeft = maxDepth(root->left);
    int dRight = maxDepth(root->right);

    return dLeft > dRight ? dLeft+1 : dRight+1;
}

Move Zeroes

Given an array nums, write a function to move all 0’s to the end of it
while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your
function, nums should be [1, 3, 12, 0, 0].

Note: You must do this in-place without making a copy of the array.
Minimize the total number of operations.

找出所有的0,然後把所有的0放到最後,但是原來非0的數字順序不能改變。
思路就是

改進的氣泡排序的方式,形象的方式就是當0與0相碰的時候,兩個0合併成一個大”0“,這個大”0“通過記錄這個大”0“的前面的位置和size表示,如果碰到的不是0的時候,就把這個數字放在大”0“後面,也就是大”0“向前前進一步。

void moveZeroes(int* nums, int numsSize) {
    int i, j;

    j = 0;
    int k = 0;
    int tmp;
    while (nums[k++] != 0);
    i = k-1;
    j = 1;
    for (; k < numsSize; k++)
        if (nums[k] != 0) {tmp = nums[k]; nums[k]= nums[i-j+1]; nums[i-j+1] = tmp; i=i+1;}
        else{j++; i++;}
}