1.最大深度问题
递归
public static int maxDepth_1(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = maxDepth_1(root.left);
int rightHeight = maxDepth_1(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
层次遍历
public static int maxDepth_2(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int ans = 0;
while (!queue.isEmpty()) {
//size表示某一层的所有元素数
int size = queue.size();
//size=0 表示一层访问完了
while (size > 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
ans++;
}
return ans;
}
2.判断平衡树
自下而上
public static boolean isBalanced_1(TreeNode root) {
return recur(root) != -1;
}
public static int recur(TreeNode root) {
if (root == null) {
return 0;
}
int left = recur(root.left);
if (left == -1) {
return -1;
}
int right = recur(root.right);
if (right == -1) {
return -1;
}
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
}
自上而下
public static boolean isBalanced_2(TreeNode root) {
if (root == null) {
return true;
}
return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced_2(root.left) && isBalanced_2(root.right);
}
private static int depth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(depth(root.left), depth(root.right)) + 1;
}
3.最小深度
递归
public static int minDepth_1(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int min_depth = Integer.MAX_VALUE;
if (root.left != null) {
min_depth = Math.min(minDepth_1(root.left), min_depth);
}
if (root.right != null) {
min_depth = Math.min(minDepth_1(root.right), min_depth);
}
return min_depth + 1;
}
层次遍历
public static int minDepth_2(TreeNode root) {
if (root == null) {
return 0;
}
int minDepth = 0;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (queue.size() > 0) {
//获取当前队列的长度,这个长度相当于 当前这一层的节点个数
int size = queue.size();
minDepth++;
for (int i = 0; i < size; ++i) {
TreeNode t = queue.remove();
if (t.left == null && t.right == null) {
return minDepth;
}
if (t.left != null) {
queue.add(t.left);
}
if (t.right != null) {
queue.add(t.right);
}
}
}
return 0;
}
4.N叉树的最大深度问题
public static int maxDepth_N(NTreeNode root) {
if (root == null) {
return 0;
} else if (root.children == null || root.children.isEmpty()) {
return 1;
} else {
List<Integer> heights = new LinkedList<Integer>();
for (NTreeNode item : root.children) {
heights.add(maxDepth_N(item));
}
return Collections.max(heights) + 1;
}
}