微软面试100题系列---把二叉查找树转换成排序的双向链表
来源:互联网 发布:东方红大数据 编辑:程序博客网 时间:2024/05/18 20:48
题目:把二叉查找树转换成排序的双向链表
输入:一个二叉查找树
输出:排序的双向链表;
要求:不能创建任何新的节点,只能调整指针的方向;
实现
思路:对二叉查找树进行中序遍历,对遍历的当前节点加入到链表末尾即可;加入链表的head和tail,当前的节点curr:
curr->next=null;curr->pre=tail;tail->next=curr;tail=curr;
实现代码:
public class Num1 { public static BSTreeNode head=null; public static BSTreeNode tail=null; /* * insert search tree to double link */ public static void main(String[] args) { //create a search tree to test BSTreeNode root=null; root=addBSTreeNode(root,10); addBSTreeNode(root,6); addBSTreeNode(root,14); addBSTreeNode(root,4); addBSTreeNode(root,8); addBSTreeNode(root,12); addBSTreeNode(root,16); inOrderBSTree(root); //print result BSTreeNode node=head; while(node.right!=null){ System.out.print(node.value+" "); node=node.right; } } public static BSTreeNode addBSTreeNode(BSTreeNode root,int value){ BSTreeNode node=new BSTreeNode(value,null,null); if(root==null){ root=node; return root; } BSTreeNode curr=root; BSTreeNode parent=null; while(curr!=null){ parent=curr; if(curr.value<value){ curr=curr.right; }else{ curr=curr.left; } } //insert node to parent's child if(parent.value<value){ parent.right=node; }else{ parent.left=node; } return root; } public static void inOrderBSTree(BSTreeNode root){ if(root==null){ return; } if(root.left!=null){ inOrderBSTree(root.left); } //System.out.println(root.value); convertIntoDoubleList(root); if(root.right!=null){ inOrderBSTree(root.right); } } private static void convertIntoDoubleList(BSTreeNode node) { node.left=tail; if(tail==null){ head=node; }else{ tail.right=node; } tail=node; }}class BSTreeNode{ int value; BSTreeNode left; BSTreeNode right; public BSTreeNode(int value,BSTreeNode left,BSTreeNode right){ this.value=value; this.left=left; this.right=right; } public BSTreeNode(int value){ this(value,null,null); }}
0 0
- 微软面试100题系列---把二叉查找树转换成排序的双向链表
- 微软面试100题 第一题 把二元查找树转变成排序的双向链表
- 微软面试(1/100)---把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表(JULY微软面试100题系列第一题)的算法思考
- 微软等面试100题筛选答案-1-二元查找树转换成一个排序的双向链表
- 面试100题系列之1将查找二叉树转换成有序的双向链表
- 微软等数据结构+算法面试100题(43)-- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表(微软面试)
- 微软面试100之1 把二元查找树转变成排序的双向链表(树)
- 二叉查找树 转换成 排序的双向链表
- 二叉查找树转换成排序的双向链表
- 【从零单排之微软面试100题系列】01之二叉查找树与双向链表
- 微软100题-第一题把二元查找树转变成排序的双向链表
- 【微软100题】001把二元查找树转变成排序的双向链表(树)
- (微软100题)把二元查找树转变成排序的双向链表
- (微软100题)1.把二元查找树转变成排序的双向链表
- 程序员面试100题(算法)之把二叉查找树转变成排序的双向链表(含二叉树前序创建、递归)
- 把二叉查找树转变成排序的双向链表
- 编程是什么,我要学吗?
- [Python模块学习]用tinify模块压缩和优化图片
- POJ 2960 S-Nim(博弈)
- GitHub与Git
- JS_对象_数组_json使用
- 微软面试100题系列---把二叉查找树转换成排序的双向链表
- TOJ 2132.Ambiguous permutations
- 【SDUT】[2146]最小子序列和
- 一位资深程序员大牛给予Java初学者的学习路线建议
- JVM调优总结(7):调优方法
- 【郑轻】[1837]LT说我不服
- String13 String12 Integer<->Roman Easy&Medium
- Android 笔记之 camera的控制---旧API
- 微软面试100题系列---设计包含min函数的栈