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答案:
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
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); } }
相关文章推荐
- <仅是自己做笔记。。。系列x>所有系列题目都来自v_JULY_v前辈的:精选微软等公司经典的算法面试100题
- 横空出世,席卷互联网--评微软等公司数据结构和算法面试100题
- 横空出世,席卷互联网--评微软等公司数据结构和算法面试100题
- [最新答案V0.3版]微软等数据结构+算法面试100题[第21-40题答案]
- (转)微软等数据结构+算法面试100题全部答案集锦
- 微软等数据结构+算法面试100题全部答案集锦
- 2011Android技术面试整理附有详细答案(包括百度、新浪、中科软等多家公司笔试面试题)
- 微软等数据结构+算法面试100题全部答案集锦
- 横空出世,席卷互联网--评微软等公司数据结构和算法面试100题 .
- 横空出世,席卷互联网--评微软等公司数据结构和算法面试100题 .
- 微软等数据结构+算法面试100题全部答案集锦
- 互联网--评微软等公司数据结构和算法面试100题 .
- 微软等数据结构+算法面试100题全部答案完整亮相
- [答案V0.1版]精选微软等数据结构+算法面试100题 [前20题]
- 微软等数据结构+算法面试100题全部答案集锦
- 互联网--评微软等公司数据结构和算法面试100题 .
- 横空出世,席卷Csdn [评微软等公司数据结构 算法面试100题] - 结构之法 算法之道
- 【转】微软等数据结构+算法面试100题全部答案集锦
- [答案V0.1版]精选微软等数据结构+算法面试100题 [前20题]
- 2011Android技术面试整理附有详细答案(包括百度、新浪、中科软等多家公司笔试面试题)