问题:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
例如:
将上图转换成下图的形式:
思路:
这道算法题的关键是中序遍历,因为这是一棵搜索二叉树,搜索二叉树中序遍历是有序的。首先我们定义三中间节点作为转储,first指向首节点,pre指向当前节点,last指向尾节点。我们通过中序遍历是所有节点变得有序,然后通过调整每个节点和当前节点的左右指针使其形成双向链表结构。中间节点连好之后最后连接首尾节点。
代码:
class Solution {
Node pre = null;
Node first = null;
Node last = null;
public Node treeToDoublyList(Node root) {
if(root==null) return root;
centransfor(root);
last = pre;
first.left = last;
last.right = first;
return first;
}
public void centransfor(Node root){
if(root == null)
{
return ;
}
centransfor(root.left);
root.left = pre;
if(pre == null){
first = root;
}
else{
pre.right = root;
}
pre = root;
centransfor(root.right);
}
}