public
class
DayStout {
static
class
TreeNode {
int
val;
TreeNode left;
TreeNode right;
TreeNode(
int
val) {
this
.val = val; }
}
static
int
bstToVine(TreeNode grand)
{
int
count =
0
;
TreeNode tmp = grand.right;
while
(tmp !=
null
) {
if
(tmp.left !=
null
) {
TreeNode oldTmp = tmp;
tmp = tmp.left;
oldTmp.left = tmp.right;
tmp.right = oldTmp;
grand.right = tmp;
}
else
{
count++;
grand = tmp;
tmp = tmp.right;
}
}
return
count;
}
static
void
compress(TreeNode grand,
int
m)
{
TreeNode tmp = grand.right;
for
(
int
i =
0
; i < m; i++) {
TreeNode oldTmp = tmp;
tmp = tmp.right;
grand.right = tmp;
oldTmp.right = tmp.left;
tmp.left = oldTmp;
grand = tmp;
tmp = tmp.right;
}
}
static
public
int
log2(
int
N)
{
int
result = (
int
)(Math.log(N) / Math.log(
2
));
return
result;
}
static
TreeNode balanceBST(TreeNode root)
{
TreeNode grand =
new
TreeNode(
0
);
grand.right = root;
int
count = bstToVine(grand);
int
h = log2(count +
1
);
int
m = (
int
)Math.pow(
2
, h) -
1
;
compress(grand, count - m);
for
(m = m /
2
; m >
0
; m /=
2
) {
compress(grand, m);
}
return
grand.right;
}
static
void
preorderTraversal(TreeNode root)
{
if
(root ==
null
)
return
;
System.out.print(root.val +
" "
);
preorderTraversal(root.left);
preorderTraversal(root.right);
return
;
}
public
static
void
main(String[] args)
{
TreeNode root =
new
TreeNode(
10
);
root.left =
new
TreeNode(
5
);
root.left.left =
new
TreeNode(
2
);
root.left.left.left =
new
TreeNode(
1
);
root = balanceBST(root);
preorderTraversal(root);
}
}