题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:二叉搜索树的中序遍历为排序的。
1、通过中序遍历递归查找每个节点的左子树和右子树。
2、每一个节点的左结点为左子树的链表最后一个节点,右结点为右子树链表的第一个节点。
3、返回链表的头结点
代码如下:
public static TreeNode pLastNodeInList=null;
public static TreeNode Convert(TreeNode pRootOfTree) {
//pLastNodeInList=null;//指向双向链表的尾结点
//反转结点
ConvertNode(pRootOfTree);
//我们需要返回头节点
TreeNode pHeadOfList=pLastNodeInList;
while(pHeadOfList!=null &&pHeadOfList.left!=null)
pHeadOfList=pHeadOfList.left;
return pHeadOfList;
}
public static void ConvertNode(TreeNode pNode){
if(pNode==null)
return;
TreeNode pCurrent=pNode;
//中序遍历左孩子
if(pCurrent.left!=null)
ConvertNode(pCurrent.left);
//当前节点的左结点位置为链表的最后一个节点
pCurrent.left=pLastNodeInList;
//链表的右结点设置为当前节点
if(pLastNodeInList!=null)
pLastNodeInList.right=pCurrent;
//将当前节点赋值给链表最后一个节点
pLastNodeInList=pCurrent;
//中序遍历右孩子
if (pCurrent.right!=null)
ConvertNode(pCurrent.right);
}