首页 > 其他 > 详细

LeetCode | Convert Sorted List to Binary Search Tree

时间:2014-03-01 22:50:00      阅读:516      评论:0      收藏:0      [点我收藏+]

题目

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

分析

递归不断构造左右子树

普通构造方法(解法1)就是每次递归调用都要去遍历找到中间的节点。

高端点的方法(解法2),类似中序遍历树的写法,先构造左子树,左子树构造完时,链表上的指针刚好指向中间节点,再构造右子树即可。

解法1

	public TreeNode sortedListToBST(ListNode head) {
		if (head == null) {
			return null;
		}

		int n = 0;
		ListNode p = head;
		while (p != null) {
			++n;
			p = p.next;
		}
		return solve(head, n - 1);
	}

	private TreeNode solve(ListNode head, int high) {
		if (high < 0) {
			return null;
		}
		int mid = high / 2;
		ListNode p = head;
		for (int i = 0; i < mid; ++i) {
			p = p.next;
		}
		TreeNode root = new TreeNode(p.val);
		root.left = solve(head, mid - 1);
		root.right = solve(p.next, high - mid - 1);
		return root;
	}

解法2

public class ConvertSortedListToBinarySearchTree {
	private ListNode head;

	public TreeNode sortedListToBST(ListNode head) {
		if (head == null) {
			return null;
		}

		this.head = head;
		int n = 0;
		ListNode p = head;
		while (p != null) {
			++n;
			p = p.next;
		}
		return solve(0, n - 1);
	}

	private TreeNode solve(int low, int high) {
		if (low > high) {
			return null;
		}
		int mid = low + (high - low) / 2;
		TreeNode left = solve(low, mid - 1);
		TreeNode root = new TreeNode(head.val);
		head = head.next;
		TreeNode right = solve(mid + 1, high);
		root.left = left;
		root.right = right;
		return root;
	}
}

LeetCode | Convert Sorted List to Binary Search Tree,布布扣,bubuko.com

LeetCode | Convert Sorted List to Binary Search Tree

原文:http://blog.csdn.net/perfect8886/article/details/20164925

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!