题干
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路
首先明白对于二叉搜索树来说,其左节点小于根节点,右节点大于根节点。其次实现排序链表意味着我们要实现中序的遍历(先左子树->根节点-> 右子树)。
使用到递归可以进行节点的遍历,在遍历节点之际,对我们所定义的头结点和尾节点进行位置的放置,即可完成想要的中序遍历直接对接上左右节点。
代码
public class Solution {
TreeNode head=null;
TreeNode tail=null;
public TreeNode Convert(TreeNode pRootOfTree) {
ReCovert(pRootOfTree);
return tail;
}
private void ReCovert(TreeNode root){
if(root==null)
return ;
ReCovert(root.left);
if(head==null){
head=root;
tail=root;
}
else{
head.right=root;
root.left=head;
head=root;
}
ReCovert(root.right);
}
}