您的位置:首页 > 理论基础 > 数据结构算法

JAVA答案整理---->微软等公司数据结构、算法面试笔试题(v_JULY_v博主发布)

2013-06-27 16:32 1121 查看
1.把二元查找树转变成排序的双向链表

题目:

输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。

要求不能创建任何新的结点,只调整指针的指向。

10

/ \

6 14

/ \ / \

4 8 12 16

转换成双向链表

4=6=8=10=12=14=16。

JAVA答案:

class Node {
public int value;
public Node left;
public Node right;

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

public Node getLeft() {
return left;
}

public void setLeft(Node left) {
this.left = left;
}

public Node getRight() {
return right;
}

public void setRight(Node right) {
this.right = right;
}

Node(int aValue) {
value = aValue;
}
}

public class ms1 {

/**
* 递归调用方式转换*/
public static Node searchTree2List(Node fatherNode, boolean isRight) {
if (fatherNode == null)
return null;

Node left = fatherNode.getLeft();
Node right = fatherNode.getRight();

/*转换左树为链表*/
if (left != null) {
Node leftRoot = searchTree2List(left, false);
leftRoot.setRight(fatherNode);
fatherNode.setLeft(leftRoot);
}

/*转换右树为链表*/
if (right != null) {
Node rightRoot = searchTree2List(right, true);
rightRoot.setLeft(fatherNode);
fatherNode.setRight(rightRoot);
}

/*获得此树转换后的链头和链尾*/
Node min = fatherNode;
Node max = fatherNode;

while (min.getLeft() != null) {
min = min.getLeft();
}
while (max.getRight() != null) {
max = max.getRight();
}

/*若转换为链表前,此树为上一级树的右子树,则返回链头;左子树,则返回链尾。以递归与上一级根节点链接。*/
if (isRight) {
return min;
} else {
return max;
}
}

public static void main(String[] args) {

Node rootNode = new Node(10);
Node node6 = new Node(6);
Node node4 = new Node(4);
Node node8 = new Node(8);
Node node14 = new Node(14);
Node node12 = new Node(12);
Node node16 = new Node(16);
rootNode.setLeft(node6);
rootNode.setRight(node14);
node6.setLeft(node4);
node6.setRight(node8);
node14.setLeft(node12);
node14.setRight(node16);

rootNode = searchTree2List(rootNode, true);

Node tmp = rootNode;
while (tmp.getRight() != null) {
System.out.println(tmp.value);
tmp = tmp.getRight();
}
System.out.println(tmp.value);

while(tmp.getLeft() != null)
{
System.out.println(tmp.value);
tmp = tmp.getLeft();
}

System.out.println(tmp.value);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐