题目
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
分析
二叉搜索树中序遍历有序,定义一个前驱节点,前驱节点与当前节点构建双向链表
代码
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val,Node _left,Node _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
Node pre = null;
Node head = null;
public Node treeToDoublyList(Node root) {
if (root == null) return null;
DFS(root);
head.left = pre;
pre.right = head;
return head;
}
void DFS(Node root) {
if (root == null) return;
//中序
treeToDoublyList(root.left);
if (pre != null) {
pre.right = root;
root.left = pre;
} else {
head = root;
}
pre = root;
treeToDoublyList(root.right);
}
}
总结 考察二搜索叉树的中序遍历,注意一下pre(前缀指针)的移动过程