Question

enter image description here

I have this Tree and wonder if this is balanced or not.

From the node 13, it is unbalanced. But other nodes are all balanced since the height difference is not more than 1 or -1.

Then how should I rebalance this tree?

Was it helpful?

Solution

The answer is yes. Node 13 has balance factor of -2. So you need to make a left rotation on node 5 and then right rotation on node 13. Like this:

After Left Rotation on Node 5:

                 13 
         |--------|--------|
        10                 17
    |----|     
    5
|---|---|
4       7

After Right Rotation on Node 13:

             10 
    |--------|--------|
    5                 13
|---|---|             |----|     
4       7                  17

And now is balanced.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top