我是java的初学者..我刚开始在线学习数据结构。我想按升序打印我添加到二叉树的值。
我创建了一个方法 print 并尝试使用这些值:
9,5,2,8,3
它打印了这个输出并停止了
2 , 3 ,8
节点必须构造函数:
构造函数 1
public Node(int value){
this.Value=value;
isEmpty=false;
this.left=new Node();
this.right=new Node();
}
构造函数 2
public Node(){
isEmpty=true;
}
添加方法:
public void add(int value) {
if (Objects.isNull(root)) {
root = new Node(value);
root.isEmpty = false;
}
Node current = root;
while (true) {
if (value < current.Value) {
if (current.left.isEmpty) {
current.left.prev = current;
current = current.left;
current.Value = value;
current.isEmpty = false;
current.left = new Node();
current.right = new Node();
break;
} else {
current = current.left;
}
} else {
if (current.right.isEmpty) {
current.right.prev = current;
current = current.right;
current.Value = value;
current.isEmpty = false;
current.left = new Node();
current.right = new Node();
break;
} else {
current = current.right;
}
}
}
}
打印方法
ArrayList<Node> list = new ArrayList();
Node current = root;while(true){
if(!current.left.isEmpty ){
if(!list.contains(current.left)){
current=current.left;
continue;
}
} else {
System.out.println(current.Value);
list.add(current);
if(!current.right.isEmpty && !list.contains(current.right)){
current=current.right;
continue;
}
current=current.prev.prev;
}
Qyouu
相关分类