算法面试题01:将一棵二元查找树转换成一个排序的双向链表(Java实现)
主要考察的内容:
- 二元查找树的定义
- 树的三种遍历方式:前序、中序、后序
- 递归
解题思路:
根据二元查找树的定义: 它首先要是一棵二元树,在这基础上它或者是一棵空树;或者是具有下列性质的二元树:
(1)若左子树不空,则左子树上所有结点的值均小于它的父结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二元查找树
所以可以判断采用中序遍历二元查找树得到的就是我们需要的目标节点顺序,这里我直接使用了Java Util包中的LinkedList(双向链表),在遍历过程中生成双向链表。
实现代码:
public class BSTreeNode {
Integer theElement;
BSTreeNode leftNode;
BSTreeNode rightNode;
public BSTreeNode() {
this(null, null, null);
}
public BSTreeNode(Integer theElement) {
this(theElement, null, null);
}
public BSTreeNode(Integer theElement, BSTreeNode leftNode,
BSTreeNode rightNode) {
this.theElement = theElement;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
public BSTreeNode insert(Integer theElement) {
if (this.theElement == null) {
this.theElement = theElement;
} else if (this.theElement > theElement) {
if (leftNode == null)
leftNode = new BSTreeNode(theElement);
else
leftNode.insert(theElement);
} else if (this.theElement < theElement) {
if (rightNode == null)
rightNode = new BSTreeNode(theElement);
else
rightNode.insert(theElement);
}
return this;
}
public List<Integer> bsTree2LinkedList() {
List<Integer> result = new LinkedList<Integer>();
if (this.theElement == null) {
return result;
}
if (this.leftNode != null) {
result.addAll(leftNode.bsTree2LinkedList());
}
result.add(this.theElement);
if (this.rightNode != null) {
result.addAll(rightNode.bsTree2LinkedList());
}
return result;
}
public static void main(String[] args) {
BSTreeNode bstree = new BSTreeNode();
bstree = bstree.insert(10).insert(6).insert(14).insert(16).insert(12)
.insert(4).insert(8);
List<Integer> result = bstree.bsTree2LinkedList();
for (Integer i : result) {
System.out.print(i + " ");
}
}
}