一、经典题。求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
题解:
①叶子节点指的是左右子树同时为空
②注意&&和||的区别,&&是两个同时满足才是true
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int run (TreeNode root) {
// 这里的四种情况看我画的图就理解了
if(root == null) { //当根节点为空,返回0
return 0;
}else if(root.left == null && root.right == null) { //当只有根节点,左右孩子节点为空,返回1
return 1;
}else if(root.left != null && root.right != null) { //当有根节点,左右孩子节点不为空
return Math.min(run(root.left),run(root.right))+1;
}else { //当有根节点,左右孩子节点有一个为空,为什么这里是max,是因为当左孩子为空,右孩子不为空时,左孩子没有孩子节点,只有右孩子才有孩子节点
return Math.max(run(root.left),run(root.right))+1;
}
}
}
二、网易魔法王国
import java.util.*;
public class Main {
public int run(TreeNode root) {
if(root == null) {
return 0;
}else if(root.left == null && root.right == null) {
return 1;
}else if(root.left != null && root.right != null) {
return Math.min(run(root.left),run(root.right))+1;
}else {
return Math.max(run(root.left),run(root.right))+1;
}
}
}