二叉搜索树与双向链表
题目
输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建新的结点,只能调整树中结点指针的指向。
class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
思路
我们可以中序遍历树中的每一个结点,这是因为中序遍历算法的特点是按照从小到大的顺序遍历二叉树的每一个结点。
代码
public class BinaryTreeConvert {
public BinaryTreeNode convert(BinaryTreeNode root) {
//指向双向链表的尾节点
BinaryTreeNode lastNodeInList = null;
convertNode(root, lastNodeInList);
//我们需要返回头结点
BinaryTreeNode head = lastNodeInList;
while(head != null && head.left != null){
head = head.left;
}
return head;
}
//使用递归进行转换
public void convertNode(BinaryTreeNode node, BinaryTreeNode lastNodeInList) {
if(node == null)
return ;
BinaryTreeNode currentNode = node;
//节点的左子节点不为空
if(currentNode.left != null){
//一直递归最左边的节点
convertNode(currentNode.left, lastNodeInList);
}
currentNode.left = lastNodeInList;
if(lastNodeInList != null){
lastNodeInList.right = currentNode;
}
lastNodeInList = currentNode;
if(currentNode.right != null){
convertNode(currentNode.right, lastNodeInList);
}
}
}