# 【python/M/105、106、108、109】构建平衡二叉树的问题（共四题）

### 实现代码

``````# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param alist, a list of integers
# @return a tree node
def sortedArrayToBST(self,alist):
if len(alist) == 0:
return None
if len(alist) == 1:
return TreeNode(alist[0])

left,right = 0,len(alist)-1
mid = (left + right ) // 2
root = TreeNode(alist[mid])
root.left = self.sortedArrayToBST(alist[:mid])
root.right = self.sortedArrayToBST(alist[mid+1:])
return root``````

### 代码

``````# 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:
""" :type head: ListNode :rtype: TreeNode """
# 需要额外空间的解法，将链表转化为数组
alist = []

while p:
alist.append(p.val)
p = p.next

return self.sortedArrayToBST(alist)

def sortedArrayToBST(self,alist):
if len(alist) == 0:
return None
if len(alist) == 1:
return TreeNode(alist[0])

left,right = 0,len(alist)-1
mid = (left + right ) // 2
root = TreeNode(alist[mid])
root.left = self.sortedArrayToBST(alist[:mid])
root.right = self.sortedArrayToBST(alist[mid+1:])
return root

``````

``````preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]``````

### 实现代码

``````# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def buildTree(self, preorder, inorder):
""" :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """
# 使用递归
if len(preorder) == 0:
return None
if len(preorder) == 1:
return TreeNode(preorder[0])
root = TreeNode(preorder[0])
index = inorder.index(root.val)
root.left = self.buildTree(preorder[1:index+1],inorder[0:index])
root.right = self.buildTree(preorder[index+1:len(preorder)],inorder[index+1:len(inorder)])
return root
``````

### 代码

``````# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def buildTree(self, inorder, postorder):
""" :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """
if len(inorder) == 0:
return None
if len(inorder) == 1:
return TreeNode(inorder[0])
root = TreeNode(postorder[len(postorder) - 1])
index = inorder.index(postorder[len(postorder) - 1])
root.left = self.buildTree(inorder[ 0 : index ], postorder[ 0 : index ])
root.right = self.buildTree(inorder[ index + 1 : len(inorder) ], postorder[ index : len(postorder) - 1 ])
return root``````

原文作者：平衡二叉树
原文地址: https://blog.csdn.net/alicelmx/article/details/82424398
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。