Make binary tree lean left

173 Views Asked by At

So I have a binary tree implementation which looks like this

struct node {
    struct node *left;
    struct node *right;
};

(the actual implementation is slightly more complex as there is additional data being stored as this is for a boolean algebra simplifier, but for the purpose of getting my point across I'll keep it simple)

basically I recieve a tree and I need to transform it so that it is completely left leaning

for example

              a
             / \
            /   \
           /     \
          /       \
         /         \
        b           \
       / \           \
      /   \           \
     /     \           \
    c       \           d
   / \       \         / \
  e   \       f       g   \
 / \   \     / \     / \   \
h   i   j   k   l   m   n   o

needs to become

              g 
             / \
            d   \
           / \   \
          a   \   \
         / \   \   \
        f   \   \   \
       / \   \   \   \
      b   \   \   \   \
     / \   \   \   \   \
    c   \   \   \   \   \
   / \   \   \   \   \   \
  e   \   \   \   \   \   \
 / \   \   \   \   \   \   \
h   i   j   k   l   m   n   o

I understand the concept of tree rotations but I don't really know how to use them (or any other algorithm for that matter) to make the tree lean completely left like the diagram above

If anyone could point me in the direction of a algorithm or other resource to do this I would be very appreciative

0

There are 0 best solutions below