一、二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int Left = maxDepth(root.left);
int Right = maxDepth(root.right);
if(Left >= Right){
return Left + 1;
}else{
return Right + 1;
}
}
}
二、不同路径
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。
问总共有多少条不同的路径?
class Solution {
public int uniquePaths(int m, int n) {
if(m == 1 || n == 1){
return 1;
}
int Down = uniquePaths(m - 1, n);
int Right = uniquePaths(m, n - 1);
return Down + Right;
}
}
此方法虽然答案正确,但会有超时错误,这是由于大量的重复计算,然而目前水平有限,实在是想不出更好的解法还得多加练习,故而做上记号,下次修改
钻研一番以后,修改代码如下
class Solution {
// 全局变量,⽤来保存计算过的只
static int[][] arr = null;
public int uniquePaths(int m, int n) {
// 创建⼀个⼆维数组
arr = new int[m][n];
return dfs(m - 1, n -1);
}
public int dfs(int i, int j) {
if(i == 0 || j == 0){
return 1;
}
// java ⾥,数组的初始值是 0,所以可以⽤ arr[i][i] 是否为 0 来判断
if(arr[i][j] != 0){
return arr[i][j];
}
// 把计算过的指保存起来
arr[i][j] = dfs(i - 1, j) + dfs(i, j - 1);
return arr[i][j];
}
}
三、数值的整数次方
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
class Solution {
public double myPow(double x, int n) {
if(n == 0){
return 1;
}else if(n < 0){
return 1 / (x * myPow(x, - n - 1));
}else if(n % 2 == 1){
return x * myPow(x, n - 1);
}else{
return myPow(x * x, n / 2);
}
}
}