將二叉搜尋樹轉換成一個排序的雙向連結串列
阿新 • • 發佈:2020-12-20
技術標籤:java
class Node {
char val;
Node left;
Node right;
Node(char val) {
this.val = val;
}
}
public class Tree {
public Node Convert(Node pRootOfTree) {
if (pRootOfTree == null) {
return null;
}
convertChild(pRootOfTree);
Node head = pRootOfTree;
while (head.left != null) {
head = head.left;
}
return head;
}
Node prev = null;
public void convertChild(Node root) {
if (root == null) {
return ;
}
convertChild(root.left);
root.left = prev;
if (prev != null) {
prev.right = root;
}
prev = root;
convertChild(root.right);
}
//列印單鏈表
public void display(Node head) {
Node cur = head;
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.right;
}
System.out.println();
}
}