题目:输入一颗二叉搜索树,将该二叉搜索树转换称一个排序的双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
在二叉搜索树中,每一个节点都有一个指向其左节点和其右节点的指针,因此我们可以利用这两个指针。将指向其左节点的指针调整为链表中指向前一个节点的指针,将其指向右节点的指针调整为链表中指向后一个节点的指针。并且由于要求转换后的链表有序,因此我们可以采用二叉搜索树的中序遍历,然后对其指针进行修改。
如下图所示:
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null)
{
return null;
}
TreeNode lastNodeInList = null;
lastNodeInList = convertHelper(pRootOfTree,lastNodeInList);
TreeNode firstNodeInList = lastNodeInList;
while(firstNodeInList.left != null)
{
firstNodeInList = firstNodeInList.left;
}
return firstNodeInList;
}
public TreeNode convertHelper(TreeNode node, TreeNode lastNode)
{
if(node.left != null)
{
lastNode = convertHelper(node.left, lastNode);
}
node.left = lastNode;
if(lastNode != null)
{
lastNode.right = node;
}
lastNode = node;
if(node.right != null)
{
lastNode = convertHelper(node.right, lastNode);
}
return lastNode;
}
}