LeetCode:104. 二叉树的最大深度 - 力扣(LeetCode)
1.思路
递归调用,最大值声明为全局常量
确定递归函数参数及其返回值:TreeNode node, int deep(不少细节要注意)
确定终止条件:if (node == null) return;
确定单层递归的逻辑:后序遍历(左右子树处理完的信息返回给根节点,即可对结果进行输出)
2.代码实现
// 递归三部曲
class Solution {
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;
}
}
// 自定义递归函数
class Solution {
int maxDeep = 0;
public int maxDepth(TreeNode root) {
deep(root, 0);
return maxDeep;
}
public void deep(TreeNode node, int deep) {
if (node == null) return;
deep++;
maxDeep = maxDeep < deep ? deep : maxDeep;
deep(node.left, deep);
deep(node.right, deep);
deep--; // 回溯
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).
LeetCode:559.n叉树的最大深度
1.思路
多叉树第一次遇到,和二叉树思路的结构相似
2.代码实现
class Solution {
int maxDeep = 0;
public int maxDepth(Node root) {
if (root == null) return 0;
int deep = 0;
if (root.children != null) {
for (int i = 0; i < root.children.size(); i++) {
Node child = root.children.get(i);
deep = Math.max(deep, maxDepth(child));
}
}
return deep + 1;
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).
LeetCode:111.二叉树的最小深度
1.思路
最小深度和最小高度可以看成一个意思,采用后序遍历分别遍历左右子树,将左右子树的结果向根节点返回即可,需要对左右子树为空的情况进行判断,左子树为空,返回右子树的最小高度,右子树为空,返回左子树的最小高度。
2.代码实现
// 递归
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (root.left == null && root.right != null) {
return right + 1;
}
if (root.right == null && root.left != null) {
return left + 1;
}
return Math.min(left, right) + 1;
}
}
// 迭代法
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(root);
int depth = 0;
while (!deque.isEmpty()) {
int size = deque.size;
depth++;
for (int i = 0; i < size; i++) {
TreeNode tmp = queue.poll();
if (tmp.left == null && tmp.right == null) {
return depth;
}
if (tmp.left != null) {
deque.offer(poll.left);
}
if (tmp.right != null) {
deque.offer(tmp.right);
}
}
}
return depth;
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).
LeetCode:222.完全二叉树的节点个数
222. 完全二叉树的节点个数 - 力扣(LeetCode)
1.思路
后序遍历,将左右子树的节点数分别返回给跟节点,两者之和即是总节点数
2.代码实现
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int left = countNodes(root.left);
int right = countNodes(root.right);
return left + right + 1;
}
}
3.复杂度分析
时间复杂度:O(logn).
空间复杂度:O(logn).