Alcott Alcott - 1 month ago 16
C++ Question

How to implement 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 gotta 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 *lchit, *rchild; //*parent;
};

Answer

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;