1.二叉树的最小深度
Leetcode 111;easy;
package tree;
public class Main0111二叉树的最小深度 {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode node1 = new TreeNode(2);
root.left = node1;
int depth = new Solution111().minDepth(root);
System.out.println(depth);
}
}
// 最小深度:从根节点到最近叶子节点的最短路径上的节点数量。
class Solution111 {
public int minDepth(TreeNode root) {
if (root == null)
return 0;
if (root.left == null)
return minDepth(root.right) + 1;
if (root.right == null)
return minDepth(root.left) + 1;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
2.二叉树的最大深度
Leetcode 104;easy;
package tree;
// 104最大深度、111最小深度、222结点个数
public class Main0104二叉树的最大深度 {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode node1 = new TreeNode(2);
TreeNode node2 = new TreeNode(3);
TreeNode node3 = new TreeNode(4);
root.left = node1;
root.right = node2;
node1.left = node3;
int depth = new Solution104().maxDepth(root);
System.out.println(depth);
}
}
class Solution104 {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
3.二叉树的结点个数
Leetcode 222;easy;
package tree;
import java.util.LinkedList;
import java.util.Queue;
public class Main0222完全二叉树的节点个数 {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode node = new TreeNode(1);
TreeNode node1 = new TreeNode(1);
root.left = node;
node.left = node1;
int nodes = new Solution222().countNodes(root);
System.out.println(nodes);
}
}
class Solution222 {
public int countNodes(TreeNode root) {
if (root == null)
return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
class Solution0222 {
public int countNodes(TreeNode root) {
if (root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int count = 1;
while (!queue.isEmpty()) {
TreeNode cur = queue.remove();
if (cur.left != null) {
queue.add(cur.left);
count++;
}
if (cur.right != null) {
queue.add(cur.right);
count++;
}
}
return count;
}
}