import java.util.*;
public class TreeNode {
private int val;
public TreeNode left, right;
private int size = 0;
public TreeNode(int val) {
this.val = val;
size = 1;
left = right = null;
}
public int getSize() {return this.size;}
public int getVal() {return this.val;}
/*
最简单的方法是遍历出整个的tree 然后取随机数进行 return, 但是那样浪费了时间o(n)和空间o(n),
还有一种方法是先找到整个tree的size 然后生成随机数, 按照遍历的顺序找到这个node,但是这样也消耗了o(n)的时间
好一点的方法是 如果在treenode中直接设立一个size的属性,这样直接就能生成一个随机数,如果这个数小于left的size 那么就去left 中找,以此类推
找到为止;
*/
public TreeNode getRandomNode() {
int leftSize = left == null ? 0 : left.getSize();
Random random = new Random();
int index = random.nextInt(size);
if(index == leftSize) {
return this;
} else if(index < leftSize) {
return left.getRandomNode();
} else {
return right.getRandomNode();
}
}
public void insertNode(int data) {
if(data <= val) {
if(left == null) {
left = new TreeNode(data);
} else {
left.insertNode(data);
}
} else {
if(right == null) {
right = new TreeNode(data);
} else {
right.insertNode(data);
}
}
size++;
return;
}
public TreeNode find(int data) {
if(val == data) {
return this;
} else if(data < val) {
return left == null ? null : left.find(data);
} else {
return right == null ? null : right.find(data);
}
}
}