109 有序鍊錶轉換二叉搜尋樹

2021-09-25 11:40:50 字數 1669 閱讀 5857

這道題是將有序鍊錶轉化成高度平衡的二叉查詢樹。

於是晚上用自己的電腦,重新在本地編譯器上手打了一遍再提交突然就好了

emmm…mark一下,可能是一些格式問題吧。

# # definition for singly-linked list.

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

# # definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

def __init__(self):

self.values =

def sortedlisttobst(self, head: listnode) -> treenode:

if head is none:

return none

temp = head

while temp is not none:

temp = temp.next

n = len(self.values)

def buildtree(x, y, m):

if x == y:

return treenode(self.values[x])

if x+1 == y:

ans1 = treenode(self.values[y])

ans1.left = treenode(self.values[x])

return ans1

if x+2 == y:

ans = treenode(self.values[m])

ans.left = treenode(self.values[x])

ans.right = treenode(self.values[y])

# ans.left, ans.right = ans1, ans2

return ans

ans = treenode(self.values[m])

ans.left = buildtree(x, m-1, (x+m-1)//2)

ans.right = buildtree(m+1, y, (m+1+y)//2)

return ans

res = buildtree(0, n-1, n//2)

return res

# if __name__ == "__main__":

# x: listnode = listnode(2)

# x.next = listnode(3)

# s = solution()

# ans = s.sortedlisttobst(x)

# print(ans.val)

提交成功以後,還意外發現,一年前也隨機pick過這題,當時嘗試用c++寫的,並且還ac了…就很神奇了(⊙o⊙)

109 有序鍊錶轉換二叉搜尋樹

給定乙個單鏈表,其中的元素按公升序排序,將其轉換為高度平衡的二叉搜尋樹。本題中,乙個高度平衡二叉樹是指乙個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。示例 給定的有序鍊錶 10,3,0,5,9 乙個可能的答案是 0,3,9,10,null,5 它可以表示下面這個高度平衡二叉搜尋樹 0 ...

109 有序鍊錶轉換二叉搜尋樹

給定乙個單鏈表,其中的元素按公升序排序,將其轉換為高度平衡的二叉搜尋樹。本題中,乙個高度平衡二叉樹是指乙個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。示例 給定的有序鍊錶 10 3,0,5,9 乙個可能的答案是 0,3,9 10,null,5 它可以表示下面這個高度平衡二叉搜尋樹 0 ...

109 有序鍊錶轉換二叉搜尋樹

109.有序鍊錶轉換二叉搜尋樹 給定乙個單鏈表,其中的元素按公升序排序,將其轉換為高度平衡的二叉搜尋樹。本題中,乙個高度平衡二叉樹是指乙個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。示例 給定的有序鍊錶 10,3,0,5,9 乙個可能的答案是 0,3,9,10,null,5 它可以表示...