題目:輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的循環雙向鏈表。要求不能創建任何新的節點,只能調整樹中節點指針的指向。
排序 節點從小到大排序,中序遍歷節點 雙向鏈表 當前節點和前一個節點 tail.right=cur cur.left=tail 循環鏈表 設置鏈表的頭結點和尾節點 head.right=tail tail.left=head
代碼實現:
public class Test30 {
/** 定義雙向鏈表的頭結點和尾節點 */
Node head;
Node tail;
/** 二叉樹的節點 */
static 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;
}
};
/**
* @Description: 輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的循環雙向鏈表。
* 要求不能創建任何新的節點,只能調整樹中節點指針的指向。
* 排序 節點從小到大排序,中序遍歷節點
* 雙向鏈表 當前節點和前一個節點 tail.right=cur cur.left=tail
* 循環鏈表 設置鏈表的頭結點和尾節點 head.right=tail tail.left=head
* @Date: 2020/6/19 19:52
* @Author: fuGuoWen
* @Return Test30.Node 雙向鏈表的頭結點
* @Throws
*/
public Node treeToDoublyList(Node root) {
if(root==null){
return null;
}
dfs(root);
head.left=tail;
tail.right=head;
return head;
}
/**
* @Description: 中序遍歷二叉樹
* @param cur 當前節點
* @Date: 2020/6/19 20:43
* @Author: fuGuoWen
* @Return 無
* @Throws 無
*/
public void dfs(Node cur){
if(cur==null){
return ;
}
dfs(cur.left);
/**
* 判斷尾結點是否爲空
* 尾結點不爲空,把當前節點鏈到鏈表的末尾,tail 向後移動
* 如果尾節點爲空,頭節點和尾節點都指向當前元素
* */
if(tail!=null){
tail.right=cur;
cur.left=tail;
tail=cur;
}else{
head=cur;
tail=cur;
}
dfs(cur.right);
}
}