1. 程式人生 > >演算法——把二元查詢樹轉變成排序的雙向連結串列(JAVA)

演算法——把二元查詢樹轉變成排序的雙向連結串列(JAVA)

輸入一棵二元查詢樹,將該二元查詢樹轉換成一個排序的雙向連結串列。 要求不能建立任何新的結點,只調整指標的指向。 這裡寫圖片描述 轉換成雙向連結串列 1=2=3=4=5=6=7=8=9=10=11=12=13=14=15。

程式碼如下

public class BinaryTree2LinkedTree {

    private static TreeNode head,tail;

    static class TreeNode{
        private int v;
        private TreeNode left;
        private TreeNode right;

        public
TreeNode(int v, TreeNode left, TreeNode right) { this.v = v; this.left = left; this.right = right; } public int getV() { return v; } public void setV(int v) { this.v = v; } public TreeNode getLeft
() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } } public
static void traversal(TreeNode node){ if(node ==null) return; if(node.getLeft()!=null) traversal(node.getLeft()); changeNode(node); if(node.getRight() != null) traversal(node.getRight()); } private static void changeNode(TreeNode node) { //初始時,雙向連結串列中無節點,head及tail均為null if (head == null) { head = node; tail = node; } else { //將新node的左指標指向當前tail,再將當前tail的右指標指向新node,最後將tail後移 node.setLeft(tail); tail.setRight(node); tail = node; } } public static void main(String[] args) { TreeNode node1 = new TreeNode(1,null,null); TreeNode node3 = new TreeNode(3,null,null); TreeNode node2 = new TreeNode(2,node1,node3); TreeNode node5 = new TreeNode(5,null,null); TreeNode node7 = new TreeNode(7,null,null); TreeNode node6 = new TreeNode(6,node5,node7); TreeNode node4 = new TreeNode(4,node2,node6); TreeNode node9 = new TreeNode(9,null,null); TreeNode node11 = new TreeNode(11,null,null); TreeNode node10 = new TreeNode(10,node9,node11); TreeNode node13 = new TreeNode(13,null,null); TreeNode node15 = new TreeNode(15,null,null); TreeNode node14 = new TreeNode(14,node13,node15); TreeNode node12 = new TreeNode(12,node10,node14); TreeNode node8 = new TreeNode(8,node4,node12); traversal(node8); while (head != null) { System.out.print(head.getV() + " "); head = head.getRight(); } } }