Implementing a parent node in AVL tree

2.1k views Asked by At

Hello guys i am learning binary trees and made progress learning the fundamentals. Now im learning AVL and writing code to balance my tree. but i hit a snag as with root node(The parent node of the tree) is not being balanced. I plan to add a parent node in the node class to keep track of the parent node but don't know to implement an AVL tree with a parent node. Please could someone show an example would be really helpful.

Node class:

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 tree:

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);
   }
  }

How do you keep track of the parent node. The parent node should be the very first element added to the list. The next nodes are it's children or descendants. How do you implement a binaryTree with a parent node. An example would be very helpful thanks.

1

There are 1 answers

0
JShell On

Since you're learning, I'll try to point you in the right direction rather than give you the code. What's generally done is to not "keep track" of the parent node at all. Nodes typically store their descendants (left and right children) only. Parent information can be found during the process of traveling down the tree, recursively. Does this help?