這期內容當中小編將會給大家帶來有關怎么在Java中利用二叉查找樹算法實現一個排序功能,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
具體如下:
/** * 無論排序的對象是什么,都要實現Comparable接口 * * @param <T> */ public class BinaryNode<T extends Comparable<T>> { private static int index = 0; // 排序下標 private static int len = 0; // 最大數組長度 private T t; // 根節點 private BinaryNode<T> left; // 左側葉子節點 private BinaryNode<T> right; // 右側葉子節點 public BinaryNode(T t) { len++; this.t = t; } /** * 往一顆書中插入值,在本質上都通過根節點一層層的判斷。 * 如果根節點不存在則新建節點 * 如果根節點存在則判斷應該在左側還是在右側插入,通常是左小右大 * * @param t */ public void insert(T t) { if (this.t.compareTo(t) > 0) { if (this.left == null) { BinaryNode<T> node = new BinaryNode<T>(t); this.left = node; } else { this.left.insert(t); } } else { if (this.right == null) { BinaryNode<T> node = new BinaryNode<T>(t); this.right = node; } else { this.right.insert(t); } } } /** * 調用私有方法 * * @return */ public Comparable<?>[] order() { Comparable<?>[] os = new Comparable[len]; order(this, os); return os; } /** * 利用中序遍歷查找整顆樹 * * @param bn * @param os */ private void order(BinaryNode<T> bn, Comparable<?>[] os) { if (bn.left == null) { os[index++] = bn.t; } else { order(bn.left, os); os[index++] = bn.t; } if (bn.right == null) { return; } else { order(bn.right, os); } } }
上述就是小編為大家分享的怎么在Java中利用二叉查找樹算法實現一個排序功能了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。