[英]How to insert a BST into an ArrayList top down, left to right?
I know how to insert a BST into an ArrayList in order [25, 50, 100, 125, 150, 180].我知道如何按 [25, 50, 100, 125, 150, 180] 的顺序将 BST 插入到 ArrayList 中。 What I would like to do is insert the tree into an ArrayList in the way it is represented in a tree.我想做的是以树中表示的方式将树插入到 ArrayList 中。 For example, [100, 50, 150, 25, null, 125, 180] would be a tree that looks like this:例如, [100, 50, 150, 25, null, 125, 180] 将是一棵如下所示的树:
100
/ \
50 150
/ \ / \
25 null 125 180
I would like to be able to put the tree into an ArrayList in this way, including the nulls.我希望能够以这种方式将树放入 ArrayList 中,包括空值。 How can I do this?我怎样才能做到这一点?
Here is the code I have now.这是我现在拥有的代码。 It will print the tree values but not the null values:它将打印树值但不打印空值:
private int height(Node<T> current){
if(current == null){
return 0;
}
else{
//
int leftHeight = height(current.left);
int rightHeight = height(current.right);
//
if (leftHeight > rightHeight) {
return (leftHeight + 1);
}
else{
return (rightHeight + 1);
}
}
}
private void printAllLevels(Node<T> current, int level){
if (current == null){
return;
}
if(level == 1){
System.out.print(current.data + " ");
}
else if (level > 1) {
printAllLevels(current.left, level - 1);
printAllLevels(current.right, level - 1);
}
}
@Override
public String toString() {
toString(this.root);
return null;
}
private void toString(Node<T> current){
int h = height(this.root);
for(int i = 1; i <= h; i++){
printAllLevels(this.root, i);
}
}
private int height(Node<T> current){
if(current == null){
return 0;
}
else{
//
int leftHeight = height(current.left);
int rightHeight = height(current.right);
//
if (leftHeight > rightHeight) {
return (leftHeight + 1);
}
else{
return (rightHeight + 1);
}
}
}
private void printAllLevels(Node<T> current, int level){
if (current == null){
System.out.print("null ");
return;
}
if(level == 1){
System.out.print(current.data + " ");
}
else if (level > 1) {
printAllLevels(current.left, level - 1);
printAllLevels(current.right, level - 1);
}
}
@Override
public String toString() {
toString(this.root);
return null;
}
private void toString(Node<T> current){
int h = height(this.root);
for(int i = 1; i <= h; i++){
printAllLevels(this.root, i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.