传入一个BST二分查找树,就可以将其转为双向链表,且返回链表头
/**
* 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
*/
public class ConvertTree2LinkedList {
//传入一个BST二分查找树,就可以将其转为双向链表,且返回链表头
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null || pRootOfTree.left == null && pRootOfTree.right == null ){
return pRootOfTree;
}
TreeNode left = Convert(pRootOfTree.left);
TreeNode leftTail = left;
while(leftTail != null && leftTail.right != null){
leftTail = leftTail.right;
}
if(leftTail != null){
//双向链表,左边指向left,右边指向right
leftTail.right = pRootOfTree;
pRootOfTree.left = leftTail;
}
TreeNode right = Convert(pRootOfTree.right);
if(right != null){
right.left = pRootOfTree;
pRootOfTree.right = right;
}
return left == null ? pRootOfTree : left;
}
}
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}