数据结构面试题1.2.1-把二元查找树转变成排序的双向链表

package questions;

/**
 * @title 把二元查找树转变成排序的双向链表
 * @question 输入一颗二元查找树,将该二元查找树转换成一个排序的双向链表。要求不能创建任何新结点,只能调整指针的指向。<br>
 *           .... 10<br>
 *           .... /\<br>
 *           ... 6 14<br>
 *           .. /\ /\<br>
 *           . 4 8 12 16<br>
 *           转换成双向链表 4=6=8=10=12=14=16
 * @author Sam
 *
 */
public class Ex1o2o1 {
	static BSTreeNode pHeader = null;// 指向循环队列头结点
	static BSTreeNode pPrevios = null;// 指向前一个结点

	/**
	 * 1.构造二叉树查找树;<br>
	 * 2.中序遍历二叉树查找,因此结点按从小到大顺序访问,假设之前访问过的结点已经调整为一个双向链表,那么<br>
	 * 3.只需要将当前结点连接至双向链表的最后一个结点即可,访问完毕后,双向链表也就调整好了。
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		BSTreeNode tree = new BSTreeNode();
		tree.add(10);
		tree.add(6);
		tree.add(14);
		tree.add(4);
		tree.add(8);
		tree.add(12);
		tree.add(16);

		inOrderBSTree(tree);

		// 验证
		System.out.print("验证正向链接:");
		BSTreeNode node = pHeader;
		while (null != node) {
			System.out.print(String.format(" %d ", node.value));
			node = node.right;
		}
		System.out.println();
		System.out.print("验证反向链接:");
		node = pPrevios;
		while (null != node) {
			System.out.print(String.format(" %d ", node.value));
			node = node.left;
		}
	}

	/**
	 * 中序遍历,同时调整指针
	 * 
	 * @param tree
	 */
	static void inOrderBSTree(BSTreeNode tree) {
		if (null == tree) {
			return;
		}
		if (null != tree.left) {
			inOrderBSTree(tree.left);
		}
		converToDoubleList(tree);
		if (null != tree.right) {
			inOrderBSTree(tree.right);
		}
	}

	/**
	 * 调整指针
	 * 
	 * @param tree
	 */
	static void converToDoubleList(BSTreeNode tree) {
		tree.left = pPrevios;// 使当前结点的左指针指向链表的上一个结点
		if (null == pPrevios) {// 若上一个结点不存在,此时双向链表不存在,因此将当前结点设为链表头结点
			pHeader = tree;
		} else {//
			pPrevios.right = tree;
		}
		pPrevios = tree;// 将当前结点设为最后一个结点
	}

}

class BSTreeNode {
	int value;// value of node
	BSTreeNode left;// left child of node
	BSTreeNode right;// right child of node

	public void add(int intValue) {
		if (0 == value) {
			value = intValue;
		} else if (intValue < value) {
			if (null == left) {
				left = new BSTreeNode();
			}
			left.add(intValue);
		} else if (intValue > value) {
			if (null == right) {
				right = new BSTreeNode();
			}
			right.add(intValue);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值