每日一题:
100.相同的树
递归思想,很好做。判断根节点是不是相同,然后递归的判断p的左子树和q的左子树是否相同。
https://leetcode-cn.com/problems/same-tree/solution/xie-shu-suan-fa-de-tao-lu-kuang-jia-by-wei-lai-bu-/
一个关于树的详细讲解,掌握递归框架,对具体的问题分析递归过程中的具体操作。
关于bst的删除操作,最后返回的是删除完目标节点的树
TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val == key) {
// 这两个 if 把情况 1 和 2 都正确处理了
if (root.left == null) return root.right;
if (root.right == null) return root.left;
// 处理情况 3
TreeNode minNode = getMin(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, minNode.val);
} else if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
}
return root;
}
作者:labuladong
链接:https://leetcode-cn.com/problems/same-tree/solution/xie-shu-suan-fa-de-tao-lu-kuang-jia-by-wei-lai-bu-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
111.二叉树的最小深度。
练习利用递归的思想,大树的最小深度可以根据子树的最小深度得出,要搞清楚递归的具体情况
1.叶子节点的定义是左孩子和右孩子都为 null 时叫做叶子节点
2.当 root 节点左右孩子都为空时,返回 1
3.当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度
4.当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值
这个题比较恶心的是不是说从根节点出发所到碰到null结束能经过的最少节点个数,而是必须要到一个叶子结点,也就是{1,2}这个测试用例要求返回的是2而不是1.
70.爬楼梯
很简单的动态规划
fn = fn-1 + fn-2
我的写法空间复杂度没有优化,把每种情况的方案数都保存在一个数组里了,题解运用滚动数组,空间复杂度O1,用一个数来不断更新得到n的时候的方案数。
class Solution {
public int climbStairs(int n) {
int p = 0, q = 0, r = 1;
for (int i = 1; i <= n; ++i) {
p = q;
q = r;
r = p + q;
}
return r;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
官方的题解二和三可真是太厉害辣
数学真狠啊
矩阵快速幂
以后再说吧