1. 程式人生 > >LeetCode Convert Sorted List to Binary Search Tree

LeetCode Convert Sorted List to Binary Search Tree

type 序列 while tree markdown 解題思路 ret list product

LeetCode解題之Convert Sorted List to Binary Search Tree


原題

給定一個升序的單向鏈表。將它轉化為高度平衡的二叉搜索樹。

註意點:

  • 同一個序列轉化成的二叉搜索樹可能有多種

樣例:

輸入: nums = 1->2->3

輸出:

  2
 / 1   3

解題思路

這題就是 Convert Sorted Array to Binary Search Tree 的升級版,能夠先把鏈表轉化為列表再解答。

假設直接用鏈表解決的話。能夠看出鏈表的特點是從頭到尾依次遍歷,由於是遞增的,所以也就是從小到大依次遍歷。而二叉所搜樹的中序遍歷的結果就是一個遞增的序列,所以僅僅要依照樹的中序遍歷的方式來構造就可以。

AC源代碼

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


# Definition for a binary tree node.
class TreeNode(object)
:
def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ node, length = head, 0 while node: node = node.next length += 1
self.curr = head return self._sortedListToBST(0, length - 1) def _sortedListToBST(self, left, right): if left > right: return None mid = (left + right) // 2 left = self._sortedListToBST(left, mid - 1) root = TreeNode(self.curr.val) root.left = left self.curr = self.curr.next root.right = self._sortedListToBST(mid + 1, right) return root if __name__ == "__main__": None

歡迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 來獲得相關源代碼。

LeetCode Convert Sorted List to Binary Search Tree