最近要搞论文了,课程也比较忙,拖了几天。
思路简单,层序或者递归做都行
// 递归
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return dfs(root);
}
public int dfs(TreeNode root) {
if (root == null) return 0;
return Math.max(dfs(root.left), dfs(root.right)) + 1;
}
}
// 层序
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int depth = 0;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
while (size -- > 0) {
TreeNode temp = q.poll();
if (temp.left != null) q.add(temp.left);
if (temp.right != null) q.add(temp.right);
}
depth ++;
}
return depth;
}
}
// 层序
class Solution {
public int minDepth(TreeNode root) {
int depth = 1;
if (root == null) return 0;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
while (size -- > 0) {
TreeNode temp = q.poll();
if (temp.left == null && temp.right == null) return depth;
if (temp.left != null) q.add(temp.left);
if (temp.right != null) q.add(temp.right);
}
depth ++;
}
return depth;
}
}
// 递归
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
return dfs(root);
}
public int dfs(TreeNode root) {
if (root == null) return 100000;
else if (root.left == null && root.right == null) return 1;
return Math.min(dfs(root.left), dfs(root.right)) + 1;
}
}
// 正常递归
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int leftHeight = minDepth(root.left);
int rightHeight = minDepth(root.right);
if (root.left != null && root.right == null) {
return 1 + leftHeight;
}
if (root.right != null && root.left == null) {
return 1 + rightHeight;
}
return 1 + Math.min(leftHeight, rightHeight);
}
}
每遍历到一个节点就加一即可,选择什么遍历方式都可。
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int leftCount = countNodes(root.left);
int rightCount = countNodes(root.right);
return leftCount + rightCount + 1;
}
}