importBinaryTree.BinaryTreeNode;
publicclass Q27 {
/**
* 题目:二叉搜索树与双向链表
* 题目说明:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
* 解题思路:1)首先理解二叉搜索树的特点是:左子树的结点值小于根节点值,根结点值小于右子树的值。
* 2)在形成的双向链表中,利用中序遍历可知,结点S的前驱是左子树结点,后继是右子树结点,将所有结点进行连接,根节点的前驱是左子树的最大值,后继是右子树的最小值;
* 3)利用递归实现中序遍历。
*/
public BinaryTreeNode Convert(BinaryTreeNode root){
BinaryTreeNode lastNodeInList =null;//lastNodeInList表示双向链表的最后一个结点。
ConvertNode(root, lastNodeInList);
//返回头结点headOfList,且双向链表可以逆向查找。
BinaryTreeNode headOfList =lastNodeInList;
while(headOfList !=null && headOfList.leftNode !=null){
headOfList = headOfList.leftNode;
}
return headOfList;
}
privatevoid ConvertNode(BinaryTreeNode root,BinaryTreeNode lastNodeInList){
if(root ==null){
return ;
}
BinaryTreeNode point = root;//point表示当前结点
if(point.leftNode !=null){//遍历二叉树的左子结点
ConvertNode(point, lastNodeInList);
}
point.leftNode = lastNodeInList;
if(lastNodeInList !=null){
lastNodeInList.rightNode = point;
}
lastNodeInList = point;
if(point.rightNode !=null){
ConvertNode(point.rightNode, lastNodeInList);
}
}
}
Q27:二叉搜索树与双向链表
最新推荐文章于 2022-09-27 14:11:21 发布