平衡二叉搜索树

huangapple go评论96阅读模式
英文:

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&lt;E&gt; n,List&lt;E&gt; list) {
	int idx = (int)Math.floor(list.size()/2);
	if(n!=null) {
	    n.element = list.get(idx);
	} else if(n==null) {
	    n = new BinaryNode&lt;E&gt;(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&lt;E&gt; build(List&lt;E&gt; 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/

huangapple
  • 本文由 发表于 2020年10月21日 21:01:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64464138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定