题目链接:力扣
解题思路:递归
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
题目链接:力扣
解题思路:递归
注意审题:最小深度是从根节点到最近叶子节点的最短路径上的节点数量
代码如下:
public int minDepth(TreeNode root) {
//终止条件
if(root == null) return 0;
//单层逻辑
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if (root.left == null && root.right != null) {
return 1 + rightDepth;
} else if (root.left != null && root.right == null) {
return 1 + leftDepth;
} else {
return Math.min(leftDepth, rightDepth) + 1;
}
}
题目链接:力扣
解题思路:递归
(一)普通二叉树的求法
代码如下:
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftNode = countNodes(root.left);
int rightNode = countNodes(root.right);
return leftNode + rightNode + 1;
}
(二) 完全二叉树的求法
代码如下:
public int countNodes2(TreeNode root) {
if(root == null) return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0;
int rightDepth = 0;
while (left != null) {
left = left.left;
leftDepth++;
}
while (right != null) {
right = right.right;
rightDepth++;
}
if(leftDepth == rightDepth) {
return (2 << leftDepth) - 1;
}
return countNodes2(root.left) + countNodes2(root.right) + 1;
}
递归依旧是老大难,只能通过刷题不断地理解,总结,形成自己的思路
拒绝内耗