Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement insertion for AVL tree without parent pointer?

I saw some articles about the implementation of AVL's rebalance() function.
After each insertion, we should check the insertion Node's ancestors for balance.
So I think, in order to check ancestors' balance, I got to know the insertion Node's parent.

But, I wonder is there any other way to do that without having to use the parent pointer?
e.g., the node struct:

struct Node {
    int data;
    struct Node *lchild, *rchild; //*parent;
};
like image 346
Alcott Avatar asked Aug 27 '11 00:08

Alcott


People also ask

Is it possible to create an AVL tree without?

The answer is... yes and no. B-trees don't need to perform rotations because they have some slack with how many different keys they can pack into a node. As you add more and more keys into a B-tree, you can avoid the tree becoming lopsided by absorbing those keys into the nodes themselves.

How is an insertion of a node into an AVL tree carried out?

How is an insertion of a node into an AVL tree carried out? (c) Insertion of a node into an AVL tree is similar to binary search tree. For inserting new node, first we have to search the position and then insert the node at its proper position. After insertion, the balance might be change.


1 Answers

You can maintain a stack to the current node while you are traversing the tree

stack<Node*> nodeStack;

When you traverse to a new node, add it to the stack, and then you have your ancestry. When you finish processing a node, pop it from the stack.

** Edit **

Elaboration for the alignment comment:

struct Node {
    int data;
    struct Node *children, *parent
};

when creating children, do it this way:

node.children = new Node[2]; or node.children = malloc(sizeof(Node) * 2);
node.children[0].parent = node;
node.children[1].parent = node;
like image 137
Mranz Avatar answered Sep 22 '22 22:09

Mranz