题目:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:
首先由于要求转换之后的链表是排好序的,我们可以中序遍历树中的每个节点,这是因为中序遍历算法的特点是按照从小到大的顺序遍历二叉树的每个节点。
具体遍历时,我们可以把树分为三部分,左子树、根、右子树。根据双向链表的定义,根节点将与左子树对应链表的最后一个节点互联,同理与右子树对应链表的第一个节点互联。理清思路就可以使用递归实现:
public class MS36 {
public DoubleLinkedList getDoubleLinkedList(TreeNode root){
if (root==null) return null;
DoubleLinkedList list = getlist(root);
return list;
}
public DoubleLinkedList getlist(TreeNode root){
DoubleLinkedList left = null;
DoubleLinkedList right = null;
DoubleLinkedList thisNode = new DoubleLinkedList(root.val);
if (root.leftchild!=null) {
left = getlist(root.leftchild);
//此时要注意,返回的left不一定是左子树对应链表的最右边,需要移位
while (left.next!=null)
left=left.next;
}
if (left!=null) {
left.next = thisNode;
thisNode.pre = left;
}
if (root.rightchild!=null) {
right = getlist(root.rightchild);
//此时要注意,返回的right不一定是右子树对应链表的最左边,需要移位
while (right.pre!=null)
right = right.pre;
}
if (right!=null) {
right.pre = thisNode;
thisNode.next = right;
}
return thisNode;
}
}