问题描述:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
分析:
首先我们定义的二元查找树 节点的数据结构如下:
private static class BSTreeNode{ BSTreeNode(int x, BSTreeNode lt, BSTreeNode rt) {value = x; left = lt; right = rt;} int value; BSTreeNode left; BSTreeNode right; }
代码实现:
package oschina.mianshi; /** * @project: oschina * @filename: IT1.java * @version: 0.10 * @author: JM Han * @date: 14:55 2015/10/19 * @comment: 将该二元查找树转换成一个排序的双向链表 * @result: */ class BSTree{ private static class BSTreeNode{ BSTreeNode(int x, BSTreeNode lt, BSTreeNode rt) {value = x; left = lt; right = rt;} int value; BSTreeNode left; BSTreeNode right; } private BSTreeNode root; private BSTreeNode head; private BSTreeNode last; public BSTree(){root = null; head = null; last = null;} public void insert(int value){ root = insert(value, root); } private BSTreeNode insert(int value, BSTreeNode t) { if (null == t) return new BSTreeNode(value, null, null); if (t.value > value) t.left = insert(value, t.left); else if (t.value < value) t.right = insert(value, t.right); else System.out.println("already exist"); return t; } public void treeToList(){ treeToList(root); } private void treeToList(BSTreeNode root){ if(null == root) return; treeToList(root.left); root.left = last; if(null == last) head = root; else last.right = root; last = root; treeToList(root.right); } public void printList(){ if(null == head) return; while(head != null) { System.out.println(head.value); head = head.right; } } } public class IT1 { public static void main(String[] args) { BSTree bsTree = new BSTree(); bsTree.insert(10); bsTree.insert(6); bsTree.insert(14); bsTree.insert(4); bsTree.insert(8); bsTree.insert(12); bsTree.insert(16); bsTree.treeToList(); bsTree.printList(); } }
时间: 2024-10-17 23:38:47