把二元查找树转变成排序的双向链表

本文介绍如何将一棵二叉查找树转换为排序的双向链表,通过中序遍历的方式,调整节点间的指针指向而不创建新节点。文章提供了一个具体的实现示例,包括双向链表和二叉查找树的定义及转换方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
   
  10
  / \
 6 14
 / \ / \
4 8 12 16
   
 转换成双向链表
4=6=8=10=12=14=16。

 

中序遍历,遍历的过程生成双向链表。

 

先实现双线链表,然后实现二叉查找树。

 

class Node {
	private int value;
	private Node pre = null;
	private Node next = null;
	private Node prior = null;

	public Node(int value) {
		this.value = value;
		prior = this;
	}

	public void insert(int value) {
		Node node = new Node(value);
		prior.next = node;
		node.pre = prior;
		prior = node;
	}

	public void print() {
		Node node = this;
		Node n = null;
		while (node != null) {
			n = node;
			System.out.print(node.value + " ");
			node = node.next;
		}
		System.out.println("-----");
		while (n != null) {
			System.out.print(n.value + " ");
			n = n.pre;
		}
	}
}

public class BiSearchTree {

	private BiSearchTree LeftTree = null;
	private BiSearchTree RightTree = null;
	private int data;

	public BiSearchTree(int data) {
		this.data = data;
	}

	public void insert(int element) {
		BiSearchTree tree = this;
		BiSearchTree insert_node = new BiSearchTree(element);
		BiSearchTree pre = null;
		boolean left = true;
		while (tree != null) {
			pre = tree;
			if (tree.data > element) {
				left = true;
				tree = tree.LeftTree;
			} else {
				left = false;
				tree = tree.RightTree;
			}
		}
		if (left) {
			pre.LeftTree = insert_node;
		} else {
			pre.RightTree = insert_node;
		}
	}

	public void exchange2Link() {
		BiSearchTree node = this;
		BiSearchTree parent = null;
		Stack stack = new Stack();
		Node twoDirLinkList = new Node(Integer.MAX_VALUE);
		do {
			while (node != null) {
				stack.push(node);
				node = node.LeftTree;
			}
			BiSearchTree opNode = (BiSearchTree) stack.pop();
			twoDirLinkList.insert(opNode.data);
			System.out.print(opNode.data + " ");
			node = opNode.RightTree;
		} while (!stack.IsEmpty() || node != null);
		twoDirLinkList.print();
	}

	public static void main(String[] args) {
		// int[] data = {5,2,3,7,4,1,8,6};
		// int[] data = {10,5,12,4,7,2,14,12,9};
		int[] data = { 10, 5, 12, 4, 7 };
		BiSearchTree tree = new BiSearchTree(data[0]);
		for (int i = 1; i < data.length; i++) {
			tree.insert(data[i]);
		}
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值