226.翻转二叉树 leetcode.com/problems/in…
104.二叉树的最大深度 leetcode.com/problems/ma…
思路:就是递归地找左子树和右子树的最大深度然后加上根节点的1就可以了
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
111.二叉树的最小深度 leetcode.com/problems/mi…
class Solution {
//因为最小深度是从根节点到最近叶子节点的最短路径上的节点数量
//叶子节点是没有左右孩子的节点
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if (root.left == null) {
return rightDepth + 1;
}
if (root.right == null) {
return leftDepth + 1;
}
// 左右结点都不为null
return Math.min(leftDepth, rightDepth) + 1;
}
}