您的位置:首页 > 其它

算法 把二叉查找树转变成排序的双向链表

2016-07-11 21:01 477 查看
记住: 树的问题都递归

概念:

双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表

二叉排序树又称二叉查找树, 或者是一棵空树,或者是具有下列性质的二叉树:

(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;

(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;

(3)左、右子树也分别为二叉排序树;

(4)没有键值相等的结点。



代码: 注意里面的创建树不是写的代码, 是默认已经创建好

package BinarySearchTreeToDoubleLinkList;

public class BinarySearchTreeToDoubleLinkList {

public static void main(String[] args) {
TreeNode root = TreeNode.createBinarySearchTree();
System.out.println("-----middleSearchBinaryTree-----");
TreeNode.middleSearch(root);
System.out.println("-----doubleLinkedList-----");
LinkedListNode.printLinkedListNode(TreeNode.first);
}
}

class TreeNode {
int nodeValue;
TreeNode leftChild;
TreeNode rightChild;
static LinkedListNode first = new LinkedListNode();

public static TreeNode createBinarySearchTree(){//int[] treeNodeArray) {
TreeNode root = new TreeNode();
//构造树略
root.nodeValue = 50;
root.leftChild = new TreeNode();
root.rightChild = new TreeNode();
root.leftChild.nodeValue=20;
root.rightChild.nodeValue=60;
root.leftChild.leftChild = new TreeNode();
root.leftChild.rightChild = new TreeNode();
root.leftChild.leftChild.nodeValue=15;
root.leftChild.rightChild.nodeValue=30;
root.rightChild.rightChild = new TreeNode();
root.rightChild.rightChild.nodeValue = 70;
return root;
}

public static void middleSearch(TreeNode root) {
if(root.leftChild==null) {
System.out.println(root.nodeValue);
LinkedListNode.addToLinkedList(first, root.nodeValue);
if(root.rightChild!=null) {
middleSearch(root.rightChild);
}
}
else {
middleSearch(root.leftChild);
System.out.println(root.nodeValue);
LinkedListNode.addToLinkedList(first, root.nodeValue);
if(root.rightChild!=null) {
middleSearch(root.rightChild);
}
}
}

}

class LinkedListNode {
int nodeValue;
LinkedListNode prev;
LinkedListNode next;

public static void printLinkedListNode(LinkedListNode first) {
LinkedListNode node = first;
while(node.next!=null) {
System.out.println(node.next.nodeValue);
node = node.next;
}
}

public static void addToLinkedList(LinkedListNode first, int value){
LinkedListNode node = first;
while(node.next!=null) {
node = node.next;
}
LinkedListNode insertNode = new LinkedListNode();
insertNode.nodeValue = value;
node.next = insertNode;
insertNode.prev = node;
insertNode.next = null;
}
}
打印结果:

-----middleSearchBinaryTree-----
15
20
30
50
60
70
-----doubleLinkedList-----
15
20
30
50
60
70
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: