【剑指Offer】二叉搜索树与双向链表

题目

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

实现

1
2
3
4
5
6
7
8
9
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private TreeNode last = null;

public TreeNode Convert(TreeNode pRootOfTree) {
ConvertNode(pRootOfTree);

while (last != null && last.left != null)
last = last.left;

return last;
}

private void ConvertNode(TreeNode root) {
if (root == null)
return;

ConvertNode(root.left);

root.left = last;
if (last != null)
last.right = root;
last = root;

ConvertNode(root.right);
}