问题:
给一个二叉查找树,把它转化成排序的双向链表,要求是不能使用额外的空间(常数空间是允许的)。
例如:
该二叉查找树的双向链表结构是 1 = 3 = 4 = 6 = 7 = 8 = 10 = 13 = 14
分析:
二叉查找树具有非常鲜明的递归结构,因此,在解决这道问题时,我们无可避免的会想到用递归。关键是如何递归呢?
因为一个节点总是有一个左节点和右节点(如果存在),对于节点 N, 只要把左节点子树的最大值返回给N,那么, 那个最大值就是 N 的前一个节点,比如对于节点8, 它的左节点子树的最大值是7,那么节点8的前一个节点就是7,同理,节点7的下一个节点是8. 对于右节点子树也还是一样。有了这样的思路,写代码不是一件何难的事情了。
public class TreeToList {
public static void main(String[] args) {
Node a = new Node(18);
Node b = new Node(8);
Node c = new Node(15);
Node d = new Node(5);
Node e = new Node(60);
Node f = new Node(50);
Node g = new Node(65);
Node h = new Node(68);
a.left = b;
b.left = d;
b.right = c;
a.right = e;
e.left = f;
e.right = g;
g.right = h;
Node t = convertNode(a, true);
while(t != null) {
System.out.println(t.value);
t = t.right;
}
}
// isRight is used to check nd is
// in the right subtree or left substree
static Node convertNode(Node nd, boolean isRight) {
if (nd == null) return null;
Node pLeft = null;
Node pRight = null;
if (nd.left != null) {
pLeft = convertNode(nd.left, false);
pLeft.right = nd;
nd.left = pLeft;
}
if (nd.right != null) {
pRight = convertNode(nd.right, true);
pRight.left = nd;
nd.right = pRight;
}
Node temp = nd;
if (isRight) {
while (temp.left != null) {
temp = temp.left;
}
} else {
while (temp.right != null) {
temp = temp.right;
}
}
return temp;
}
}
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
left = null;
right = null;
}
}
转载请注明出处:
http://blog.csdn.net/beiyeqingteng
参考: http://zhedahht.blog.163.com/blog/static/254111742007127104759245/