Professional Documents
Culture Documents
Balancing a Tree
We said previously that Td
could be as large as n 1 due to a lousy insertion order.
Balancing a Tree
public void balance() { int[] A = new int[size()]; toArray(root, A, 0); root = null; size=0; // reinsert elements in "binary search" order int start = 0; int end = A.length-1; int mid = (start+end)/2; root = new BSTNode(A[mid], null, null); size += 1; add(root, A, start, mid-1); add(root, A, mid+1, end); }
ECE242 Fall 2007 Data Structures in Java, Prof. Mettu
Balancing a Tree
public void add(BSTNode r, int[] A, int start, int end) { if (start <= end) { int mid = (start+end)/2; if (A[mid] < r.key) { r.left = new BSTNode(A[mid], null, null); size += 1; add(r.left, A, start, mid-1); add(r.left, A, mid+1, end); } else { r.right = new BSTNode(A[mid], null, null); size += 1; add(r.right, A, start, mid-1); add(r.right, A, mid+1, end); } } }
ECE242 Fall 2007 Data Structures in Java, Prof. Mettu
Balancing a Tree
public void add(BSTNode r, int[] A, int start, int end) { if (start <= end) { int mid = (start+end)/2; if (A[mid] < r.key) { r.left = new BSTNode(A[mid], null, null); size += 1; add(r.left, A, start, mid-1); add(r.left, A, mid+1, end); } else { r.right = new BSTNode(A[mid], null, null); size += 1; add(r.right, A, start, mid-1); add(r.right, A, mid+1, end); } } Handling duplicates is a little trickier, we cant }
= k
i
i=1
n/k (n/k + 1) = k 2 2 n n = + 2k 2
ECE242 Fall 2007 Data Structures in Java, Prof. Mettu
Balancing Trees
If k is a constant, then the cost per insertion after all insertions have been made is O(n). In a tree that is balanced at all times, after n insertions, the cost per insertion is only O(log2 n) ... Can we always keep the tree balanced?
ECE242 Fall 2007 Data Structures in Java, Prof. Mettu
Tree Rotations
Luckily, we can modify the structure of a tree we have already built:
x y T3 T1 T2
right rotation
y x T1 T2 T3
Tree Rotations
Luckily, we can modify the structure of a tree we have already built:
x y T1 T2 T3 T1 T2
left rotation
y x T3