说明:
1.二叉排序树又名二叉搜索树;
2.二叉树转成的双向链表是排好序的;
3.总共有三种方法实现,但都是基于中序遍历。
(一)返回双向链表的头结点
// return the head of doubleLink
BinaryTreeNode convertToDoubleLink1(BinaryTreeNode currentRoot){
if(currentRoot == null){
return null;
}
// currentRoot not equal to null
BinaryTreeNode leftHead = null;
if(currentRoot.left != null){
leftHead = this.convertToDoubleLink1(currentRoot.left);
}
if(leftHead != null){
BinaryTreeNode leftTail = leftHead;
while(leftTail.right != null){
leftTail = leftTail.right;
}
leftTail.right = currentRoot;
currentRoot.left = leftTail;
}
BinaryTreeNode rightHead = null;
if(currentRoot.right != null){
rightHead = this.convertToDoubleLink1(currentRoot.right);
}
if(rightHead != null){
rightHead.left = currentRoot;
currentRoot.right = rightHead;
}
return leftHead != null? leftHead : currentRoot;
}
(二)返回双向链表的尾结点
//return the tail of doubleLink
BinaryTreeNode convertToDoubleLink2(BinaryTreeNode currentRoot){
if(currentRoot == null){
return null;
}
BinaryTreeNode leftTail = null;
if(currentRoot.left != null){
leftTail = this.convertToDoubleLink2(currentRoot.left);
}
if(leftTail != null){
leftTail.right = currentRoot;
currentRoot.left = leftTail;
}
BinaryTreeNode rightTail = null;
if(currentRoot.right != null){
rightTail = this.convertToDoubleLink2(currentRoot.right);
}
if(rightTail != null){
BinaryTreeNode rightHead = rightTail;
while(rightHead.left != null){
rightHead = rightHead.left;
}
rightHead.left = currentRoot;
currentRoot.right = rightHead;
}
return rightTail != null? rightTail : currentRoot;
}
(三)返回双向链表的头结点或者尾结点// return the head or tail by asLeft
// if left tree return tail otherwise return head
BinaryTreeNode convertToDoubleLink(BinaryTreeNode t, boolean asLeft){
if(t == null){
return null;
}
// t not equal to null
BinaryTreeNode pLeft = null;
BinaryTreeNode pRight = null;
if(t.left != null){
pLeft = this.convertToDoubleLink(t.left, true);
}
if(pLeft != null){
pLeft.right = t;
t.left = pLeft;
}
if(t.right != null){
pRight = this.convertToDoubleLink(t.right, false);
}
if(pRight != null){
pRight.left = t;
t.right = pRight;
}
BinaryTreeNode returnNode = t;
if(asLeft){
while(returnNode.right != null){
returnNode = returnNode.right;
}
}else{
while(returnNode.left != null){
returnNode = returnNode.left;
}
}
return returnNode;
}