問題描述:java
輸入一棵二元查找樹,將該二元查找樹轉換成一個排序的雙向鏈表。
要求不能建立任何新的結點,只調整指針的指向。node
10
/ \
6 14
/ \ / \
4 8 12 16數據結構
轉換成雙向鏈表
4=6=8=10=12=14=16。spa
分析:指針
首先咱們定義的二元查找樹 節點的數據結構以下:code
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.IT100; /** * @project: oschina * @filename: IT1.java * @version: 0.10 * @author: JM Han * @date: 14:55 2015/10/19 * @comment: 將該二元查找樹轉換成一個排序的雙向鏈表 * @result: */ class BSTree1 { 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 BSTree1(){root = null; head = null; last = null;} public void insert(int value){ root = insert(root, value); } private BSTreeNode insert(BSTreeNode t, int value) { if (null == t) return new BSTreeNode(value, null, null); if (t.value > value) t.left = insert(t.left, value); else if (t.value < value) t.right = insert(t.right, value); 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); //previous pointer root.left = last; if(null == last) head = root; else //next pointer last.right = root; //last is the current root node 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) { BSTree1 bsTree = new BSTree1(); 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(); } }
輸出:io
4 6 8 10 12 14 16