题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
链接:https://www.nowcoder.com/questionTerminal/947f6eb80d944a84850b0538bf0ec3a5
package offer;
public class Solution36 {
TreeNode head = null;
TreeNode tail = null;
public TreeNode Convert(TreeNode pRootOfTree) {
// 递归调用到叶子节点的左右结点的话,返回null
if (pRootOfTree == null)
return null;
// 一直递归到最左叶节点,将左子树构造成链表
Convert(pRootOfTree.left);
if (tail == null) {
head = tail = pRootOfTree;
} else { // 把根结点插入到双向链表的右边,tail向后移动
tail.right = pRootOfTree;
pRootOfTree.left = tail;
tail = pRootOfTree;
}
Convert(pRootOfTree.right); // 把右叶子节点也插入到双向链表
return head; // 返回双向链表的头结点
}
}