java之二叉搜索树转换为双向链表

题目:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

分析:可以用中序遍历树中的每一个结点,当遍历根节点时,把树看成三部分:根结点,根结点的左子树,根结点的右子树。

          先将根结点转换为双向链表,再将左子树和右子树转换为双向链表。

java代码: 

package Tree;

public class ConverToLinklist {
	private Node root;

	private class Node {
		private Node left;
		private Node right;
		private int data;

		public Node(int data) {
			this.left = null;
			this.right = null;
			this.data = data;
		}
	}

	public ConverToLinklist() {
		root = null;
	}

	public void buildTree(Node node, int data) {
		if (root == null) {
			root = new Node(data);
		} else {
			if (data < node.data) {
				if (node.left == null) {
					node.left = new Node(data);
				} else {
					buildTree(node.left, data);
				}
			} else {
				if (node.right == null) {
					node.right = new Node(data);
				} else {
					buildTree(node.right, data);
				}
			}
		}
	}

	/**
	 * 将二叉树转换为双向链表
	 */
	private Node last = null;;

	public void ConvertNode(Node node) {

		if (node == null)
			return;

		if (node.left != null)
			ConvertNode(node.left);
		node.left = last;

		if (last != null)
			last.right = node;
		last = node;
		if (node.right != null)
			ConvertNode(node.right);

	}

	public void print(Node node) {

		Node r = node;
		while (r != null) {
			System.out.print(r.data + " ");
			r = r.right;
		}
	}

	public static void main(String[] args) {
		int[] a = { 2, 4, 12, 45, 21, 6, 111 };
		ConverToLinklist bTree = new ConverToLinklist();
		for (int i = 0; i < a.length; i++) {
			bTree.buildTree(bTree.root, a[i]);
		}
		bTree.ConvertNode(bTree.root);
		bTree.print(bTree.root);

	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值