Lintcode177 Convert Sorted Array to Binary Search Tree With Minimal Height solution 题解

【题目描述】

Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.

【注】There may exist multiple valid solutions, return any of them.

给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

【注】可能有多有效解存在,返回其中一个即可。

【题目链接】

www.lintcode.com/en/problem/convert-sorted-array-to-binary-search-tree-with-minimal-height/

【题目解析】

此题需要将一个排好序的链表转成一个平衡二叉树。我们知道,对于一个二叉树来说,左子树一定小于根节点,而右子树大于根节点。所以我们需要找到链表的中间节点,这个就是根节点,链表的左半部分就是左子树,而右半部分则是右子树,我们继续递归处理相应的左右部分,就能够构造出对应的二叉树了。

这题的难点在于如何找到链表的中间节点,可以通过fast,slow指针来解决,fast每次走两步,slow每次走一步,fast走到结尾,那么slow就是中间节点了。

【参考答案】

www.jiuzhang.com/solutions/convert-sorted-array-to-binary-search-tree-with-minimal-height/

你可能感兴趣的:(Lintcode177 Convert Sorted Array to Binary Search Tree With Minimal Height solution 题解)