[英]Implementing a parent node in AVL tree
大家好,我正在學習二叉樹,並且在學習基礎知識方面取得了進步。 現在,我正在學習AVL並編寫代碼來平衡我的樹。 但是我遇到了根節點(樹的父節點)不平衡的問題。 我計划在節點類中添加一個父節點來跟蹤父節點,但是不知道要用父節點實現AVL樹。 請有人舉一個例子會很有幫助。
節點類:
public class BinaryNode<T> {
private BinaryNode<T> parent;
private BinaryNode<T> leftChild;
private BinaryNode<T> rightChild;
private int height;
private T data;
public BinaryNode(T data) {
this(data, null,null,null,0)'
}
public BinaryNode(T data, BinaryNode<T> parent, BinaryNode<T> leftChild, BinaryNode<T> rightChild, int height) {
this.data=data;
this.parent = parent;
this.leftChild= leftChild;
this.rightChild = rightChild;
this.height = 0;
}
AVL樹:
public class AVLTree {
protected BinaryNode<T> root;
public AVLTree() {}
public AVLTree(T data) {
root = new BinaryNode<T>(data);
}
public void insert(T data) {
BinaryNode<T> newNode = new BinaryNode<T>(data);
if(root == null){
root = newNode;
}
else {
insert(root, newNode);
}
}
您如何跟蹤父節點。 父節點應該是添加到列表中的第一個元素。 下一個節點是它的子代或后代。 如何實現帶有父節點的binaryTree。 一個例子將非常有幫助,謝謝。
由於您正在學習,因此我將嘗試為您指明正確的方向,而不是給您代碼。 通常要做的是根本不“跟蹤”父節點。 節點通常僅存儲其后代(左子節點和右子節點)。 父信息可以在遞歸樹的過程中找到。 這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.