简单的leetcode(一)

本文深入探讨了二叉树操作中的反转树问题和寻找最大深度的方法,通过递归实现解决方案。同时,介绍了如何优化数组中0元素的移动,确保非零元素顺序不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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++;}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值