JAVA答案整理---->微软等公司数据结构、算法面试笔试题(v_JULY_v博主发布)

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

4=6=8=10=12=14=16。


JAVA答案:

class Node {
	public int value;
	public Node left;
	public Node right;

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	public Node getLeft() {
		return left;
	}

	public void setLeft(Node left) {
		this.left = left;
	}

	public Node getRight() {
		return right;
	}

	public void setRight(Node right) {
		this.right = right;
	}

	Node(int aValue) {
		value = aValue;
	}
}

public class ms1 {

	/**
	 * 递归调用方式转换*/
	public static Node searchTree2List(Node fatherNode, boolean isRight) {
		if (fatherNode == null)
			return null;

		Node left = fatherNode.getLeft();
		Node right = fatherNode.getRight();
		
		/*转换左树为链表*/
		if (left != null) {
			Node leftRoot = searchTree2List(left, false);
			leftRoot.setRight(fatherNode);
			fatherNode.setLeft(leftRoot);
		}
		
		/*转换右树为链表*/
		if (right != null) {
			Node rightRoot = searchTree2List(right, true);
			rightRoot.setLeft(fatherNode);
			fatherNode.setRight(rightRoot);
		}

		/*获得此树转换后的链头和链尾*/
		Node min = fatherNode;
		Node max = fatherNode;

		while (min.getLeft() != null) {
			min = min.getLeft();
		}
		while (max.getRight() != null) {
			max = max.getRight();
		}

		/*若转换为链表前,此树为上一级树的右子树,则返回链头;左子树,则返回链尾。以递归与上一级根节点链接。*/
		if (isRight) {
			return min;
		} else {
			return max;
		}
	}
	

		

	public static void main(String[] args) {
		
		Node rootNode = new Node(10);
		Node node6 = new Node(6);
		Node node4 = new Node(4);
		Node node8 = new Node(8);
		Node node14 = new Node(14);
		Node node12 = new Node(12);
		Node node16 = new Node(16);
		rootNode.setLeft(node6);
		rootNode.setRight(node14);
		node6.setLeft(node4);
		node6.setRight(node8);
		node14.setLeft(node12);
		node14.setRight(node16);
		
		
		rootNode = searchTree2List(rootNode, true);

		Node tmp = rootNode;
		while (tmp.getRight() != null) {
			System.out.println(tmp.value);
			tmp = tmp.getRight();
		}
			System.out.println(tmp.value);
			
			while(tmp.getLeft() != null)
			{
				System.out.println(tmp.value);
				tmp = tmp.getLeft();
			}
			
			System.out.println(tmp.value);
	}

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值