第二十五天算法设计
BinaryTree 类:
java
package suanfa;
public class BinaryTree {
// 定义树的节点类
private static class Node {
int value;
Node left, right;
public Node(int value) {
this.value = value;
left = right = null;
}
}
private Node root;
// 构造函数,初始化空树
public BinaryTree() {
root = null;
}
// 插入节点到二叉树
public void insert(int value) {
root = insertRec(root, value);
}
// 递归的插入节点
private Node insertRec(Node root, int value) {
if (root == null) {
root = new Node(value);
return root;
}
if (value < root.value) {
root.left = insertRec(root.left, value);
} else if (value > root.value) {
root.right = insertRec(root.right, value);
}
return root;
}
// 计算二叉树的最大深度
public int maxDepth() {
return maxDepthRec(root);
}
// 递归计算二叉树的最大深度
private int maxDepthRec(Node root) {
if (root == null) {
return 0; // 空树的深度为 0
}
// 计算左子树的深度
int leftDepth = maxDepthRec(root.left);
// 计算右子树的深度
int rightDepth = maxDepthRec(root.right);
// 返回最大深度 + 1(当前节点)
return Math.max(leftDepth, rightDepth) + 1;
}
}
BinaryTreeTest 类:
java
package suanfa;
public class BinaryTreeTest {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
// 插入节点
tree.insert(4);
tree.insert(2);
tree.insert(6);
tree.insert(1);
tree.insert(3);
tree.insert(5);
tree.insert(7);
// 计算并输出最大深度
System.out.println("二叉树的最大深度: " + tree.maxDepth());
}
}
录制: untitled2 – Insertion.java
录制文件:https://meeting.tencent.com/crm/KzGGkGE85d
浙公网安备 33010602011771号