打印二叉树的工具类,参考:打印二叉树
二叉树节点
/**
* Definition for a binary tree node.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
构建二叉树工具类
import java.util.Random;
public class BinaryTreeBuilder {
private static Random random = new Random();
private int level; // 需要生成的二叉树的层级
private double leftProbability; // 左子树生成概率
private double rightProbability; // 右子树生成概率
private int value; // need to know: 构建前自动赋值
public BinaryTreeBuilder(int level) {
// 左右子树生成概率,默认为 100%
this(level, 1, 1);
}
public BinaryTreeBuilder(int level, double leftProbability, double rightProbability) {
this.level = level;
this.leftProbability = leftProbability;
this.rightProbability = rightProbability;
}
public TreeNode build() {
value = 1;
return buildTree(level);
}
private TreeNode buildTree(int level) {
if (level == 0) return null;
TreeNode root = new TreeNode(value++);
if (random.nextDouble() <= leftProbability) {
root.left = buildTree(level - 1);
}
if (random.nextDouble() <= rightProbability) {
root.right = buildTree(level - 1);
}
return root;
}
}
- 构建满二叉树,并打印到控制台。
public class BinaryTreeDemo {
public static void main(String[] args) {
TreeNode root = new BinaryTreeBuilder(3).build();
BinaryTreePrinter.print(root);
}
}
控制台输出如下:
maxLevel: 3
level[1] 节点宽度[ 16]===| 1
===| ┌───┴───┐
level[2] 节点宽度[ 8]===| 2 5
===| ┌─┴─┐ ┌─┴─┐
level[3] 节点宽度[ 4]===| 3 4 6 7
- 构建任意二叉树,并打印到控制台:
public class BinaryTreeDemo {
public static void main(String[] args) {
TreeNode root = new BinaryTreeBuilder(4, 0.8, 0.7).build();
BinaryTreePrinter.print(root);
}
}
控制台输出如下:
maxLevel: 4
level[1] 节点宽度[ 32]===| 1
===| ┌───────┴───────┐
level[2] 节点宽度[ 16]===| 2 5
===| └───┐ ┌───┴───┐
level[3] 节点宽度[ 8]===| 3 6 8
===| ┌─┘ └─┐ ┌─┴─┐
level[4] 节点宽度[ 4]===| 4 7 9 10
网友评论