搜索二叉树转换为双向链表
将一个搜索二叉树转换为双向链表,left执行下一个元素,right指向上一个元素,一种比较简洁的实现如下,除去测试代码,仅20多行代码:
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
}
}
public class Main1 {
public static void main(String[] args) {
Node root = new Node(4); root.left = new Node(2); root.right = new Node(6);
root.left.left = new Node(1); root.left.right = new Node(3);
root.right.left = new Node(5); root.right.right = new Node(7);
Node cur = root;
Node res = null;
while(cur.left != null) {
cur = cur.left;
}
res = cur;
Node pre = null;
transfer(root, pre);
//打印转换后的数据
cur = res;
while(cur.right != null) {
System.out.print(cur.value + " ");
cur = cur.right;
}
System.out.println(cur.value);
while(cur.left != null) {
System.out.print(cur.value + " ");
cur = cur.left;
}
System.out.println(cur.value);
}
public static Node transfer(Node root, Node pre) {
if(root == null) {
return pre;
}
pre = transfer(root.left, pre);
if(pre == null) {
pre = root;
root.left = null;
} else {
pre.right = root;
root.left = pre;
pre = root;
}
pre = transfer(root.right, pre);
return pre;
}
}