Download presentation

Presentation is loading. Please wait.

Published byEileen Worman Modified about 1 year ago

1
Rotating Nodes How to balance a node that has become unbalanced after the addition of one new node.

2
Detect Imbalance If ( a new node is added to either of node N's children ) rebalance( N )

3
Node rebalance( Node N ) int diff = N.left.getHeight() - N.right.getHeight(); if ( diff > 1 ) if ( N.left.left.getHeight() > N.left.right.getHeight() ) N = rotateRight( N ) else N = rotateLeftRight( N ) else if ( diff < -1 ) if ( N.right.right.getHeight() > N.right.left.getHeight() ) N = rotateLeft( N ) else N = rotateRightLeft( N ) // else, no rebalancing necessary return N

4
Balanced Search Trees

5
UnBalanced Search Trees

6
Unbalanced as result of adding a new node to the left subtree of the left subtree return results of a single rotate right unbalanced Node rotateRight( Node nodeN ) nodeC = nodeN.left nodeN.left = nodeC.right nodeC.right = nodeN return nodeC nodeN nodeC balanced

7
Unbalanced as result of adding a new node to the right subtree of the right subtree return results of a single rotate left unbalanced Node rotateLeft( Node nodeN ) nodeC = nodeN.right nodeN.right = nodeC.left nodeC.left = nodeN return nodeC nodeN nodeC balanced

8
Unbalanced as result of adding a new node to the left subtree of the right subtree return results of a right-left rotate Node rotateRightLeft( Node nodeN ) nodeC = nodeN.right nodeN.right = rotateRight(nodeC) return rotateLeft(nodeN) unbalanced nodeN nodeC balanced

9
Unbalanced as result of adding a new node to the right subtree of the left subtree return results of a left-right rotate Node rotateLeftRight( Node nodeN ) nodeC = nodeN.left nodeN.left = rotateLeft(nodeC) return rotateRight(nodeN) balanced unbalanced nodeN nodeC

Similar presentations

© 2016 SlidePlayer.com Inc.

All rights reserved.

Ads by Google