class TreeNode{
int val;
TreeNode left;
TreeNode right;
//构造方法,用于创建具有给定值的新节点
TreeNode(int val){
this.val=val;
this.left=null;//左子节点
this.right=null;//右子节点
}
}
public class BinaryTree{
private TreeNode root;//二叉树的根节点
//构造方法,创建一个空的二叉树
public BinaryTree(){
this.root=null;
}
//插入节点
public void insert(int val){
root=insertRec(root,val);
}
//递归的插入节点
private TreeNode insertRec(TreeNode root,int val){
//如果当前节点为空,说明找到了合适的位置,创建一个新节点
if(root==null){
root=new TreeNode(val);
return root;
}
//随机选择左子树或右子树来插入节点
if(Math.random()<0.5){
root.left=insertRec(root.left,val);
}else{
root.right=insertRec(root.right,val)
}
return root;
}
}