题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof
Java(中序遍历二叉搜索树)
/*
// 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, head;
public void DFS(Node cur){
if(cur == null)
return;
DFS(cur.left);
if(pre != null){
pre.right = cur;
}else{
head = cur;
}
cur.left = pre;
pre = cur;
DFS(cur.right);
return;
}
public Node treeToDoublyList(Node root) {
if(root == null)
return null;
DFS(root);
head.left = pre;
pre.right = head;
return head;
}
}