英文:
Balance a binary search tree
问题
public void build(BinaryNode<E> n, List<E> list) {
int idx = (int)Math.floor(list.size()/2);
if(n != null) {
n.element = list.get(idx);
} else if(n == null) {
n = new BinaryNode<E>(list.get(idx));
}
if(!list.subList(0, idx).isEmpty()) {
build(n.left, list.subList(0, idx));
}
if(!list.subList(idx + 1, list.size()).isEmpty() ){
build(n.right, list.subList(idx + 1, list.size()));
}
return;
}
英文:
I'm trying to implement a binary search tree class in Java with a method that can rebalance the tree if there's a difference in height. I'm trying to do it by first storing the value of the nodes in an List (an attribute of the class).
I then want to take the middle element of this list and assign this to the root of the tree. After this I take the left- and right part of the list and do the same thing recursively to the left- and right children of the root and so on.
My algorithm doesn't seem to work though and I don't understand what I'm doing wrong. I wonder if someone can take a look at my code and explain what the problem is? What I do is basically pass the ordered list of elements of the tree (an attribute of the class) and the root into the function below:
public void build(BinaryNode<E> n,List<E> list) {
int idx = (int)Math.floor(list.size()/2);
if(n!=null) {
n.element = list.get(idx);
} else if(n==null) {
n = new BinaryNode<E>(list.get(idx));
}
if(!list.subList(0,idx).isEmpty()) {
build(n.left,list.subList(0,idx));
}
if(!list.subList(idx+1,list.size()).isEmpty() ){
build(n.right,list.subList(idx+1,list.size()));
}
return;
}
Kind regards,
答案1
得分: 1
Java方法调用是“按值传递”的。这意味着更改参数(例如您的情况中的 n
)不会影响方法外部的情况。
尝试像这样定义您的方法:
public BinaryNode<E> build(List<E> list) { ... }
英文:
Java method calls are "call by value". This means changing a parameter (like n
in your case) has no effect outside of the method.
Try to define your method like this
public BinaryNode<E> build(List<E> list) { ... }
答案2
得分: 1
尝试调查AVL树
一些有用的链接:
https://en.wikipedia.org/wiki/AVL_tree
https://www.geeksforgeeks.org/avl-tree-set-1-insertion/
英文:
Try investigating about AVL tree
Some useful links:
https://en.wikipedia.org/wiki/AVL_tree
https://www.geeksforgeeks.org/avl-tree-set-1-insertion/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论