1. 题目
- 二叉树的最大深度:给定一个二叉树,找出其最大深度(离根节点最远的路径节点个数)
- 二叉树的最小深度:给定一个二叉树,找出其最小深度(离根节点最近的路径节点个数)
- 生成有效的括号组合:给定数字n,写出一个函数,把所有闭合的括号组合输出,n代表生成括号的对数。
2. 算法题解题
2.1 二叉树的最大深度:给定一个二叉树,找出其最大深度(离根节点最远的路径节点个数)
解法1:深度优先DFS,递归
分别将左右子树的最大深度算出来再加1即当前二叉树的最大深度。
时间复杂度O(n),空间复杂度O(1)
public int maxDepth(TreeNode root){
if (root == null){
return 0;
}else{
int left = maxDepth(root.left);
int right = maxDepth(root.right);
int max = Math.max(left, right) + 1;
return max;
}
}
2.2 二叉树的最小深度:给定一个二叉树,找出其最小深度(离根节点最近的路径节点个数)
解法1:深度优先DFS,递归
分别将左右子树的最小深度算出来再加1即当前二叉树的最小深度。
时间复杂度O(n),空间复杂度O(1)
public int minDepth (TreeNode root){
if (root == null)
return 0;
if (root.left== null && root.right == null)
return 1;
int minDepth = Integer.MIN_VALUE;
if (root.left != null)
minDepth = Math.min(minDepth(root.left), minDepth);
if (root.right != null)
minDepth = Math.min(minDepth(root.right), minDepth);
return minDepth + 1;
}
解法2: 广度优先搜索,迭代
使用队列辅助,按顺序取出TreeNode,只要第一个节点是叶子节点,那么就返回当前节点的深度即可。
public int minDepth(TreeNode root){
LinkedList<Pair<TreeNode, Integer>> pairs = new LinkedList<>();
if (root == null)
return 0;
//将根节点放入队列
pairs.add(new Pair<TreeNode, Integer>(root, 1));
int minDepth = 0;
while (!pairs.isEmpty()){
// 先进先出
Pair<TreeNode, Integer> pair = pairs.poll();
TreeNode node = pair.first;
minDepth = pair.second;
if (node.left == null && node.right == null)
break;
if (node.left != null)
pairs.add(new Pair<TreeNode, Integer>(node.left, minDepth +1));
if (node.right != null)
pairs.add(new Pair<TreeNode, Integer>(node.right, minDepth + 1));
}
return minDepth;
}
2.3 生成有效的括号组合:给定数字n,写出一个函数,把所有闭合的括号组合输出,n代表生成括号的对数
解法1: 回溯法
判断括号是否有效,再继续添加有效括号,直到左右括号匹配,并且字符串长度为2*n时,添加到集合中。再执行递归剩余的逻辑,不断穷举,这个问题比较抽象。
时间复杂度O(2n) 空间复杂度 O(n)
public static List generateParenthesis(int n){
List combinations = new ArrayList<>();
addGenerateOneByOne(combinations, "", 0, 0 ,n);
return combinations;
}
private static void addGenerateOneByOne(List<String> combinations, String s, int open, int close, int max) {
if (s.length() == max *2)
combinations.add(s);
if (open < max)
addGenerateOneByOne(combinations, s.concat("("), open +1, close, max);
if (close < open)
addGenerateOneByOne(combinations, s.concat(")"), open, close + 1, max);
}