JZ26-二叉搜索树与双向链表
题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解题思路:转换成排序的双向链表,首先就能想到对二叉搜索树进行中序遍历就是有序的,遍历过程中,从头开始每取到一个节点就可以将他和之前的节点进行从新构建关系。我这里用反中序遍历,从大到小排列,连接到最后返回的就是最小的那个节点,也就是头结点。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
/**
* @author 枫叶火火
*/
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
//获取根节点
TreeNode pHead = convertList(pRootOfTree, null);
return pHead;
}
//转换成双向链表,参数为当前节点和下一个节点,从后往前,从大往小进行组装
//类似于中序遍历,我这里将中序遍历反过来,最后直接返回最小节点
TreeNode convertList(TreeNode node, TreeNode nextNode){
//当前节点为空,直接返回
if(node == null){
return null;
}
//操作左子节点
if(node.right != null){
nextNode = convertList(node.right, nextNode);
}
//当前节点的右节点为下一个节点
node.right = nextNode;
//如果下一个节点不是空,下一个节点的左节点为上一节点
if(nextNode != null){
nextNode.left = node;
}
//将当前节点定为下一节点
nextNode = node;
//操作右子节点
if(node.left != null){
nextNode = convertList(node.left, nextNode);
}
return nextNode;
}
}