有序数组转换二叉树搜索

时间:2022-09-03 10:27:52

数组list1 = [1,2,3,4,5,6,7]

先找到中点,作为根节点,然后左边都比根节点小,右边都比根节点大

然后左右两边又同样找到根节点,利用递归,左节点都比根节点和右节点小,右节点都比左节点和根节点大

有序数组转换二叉树搜索

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

class Solution:
    def listtotree(self, A):
        if len(A) == 0:
            return None
        left, right = 0, len(A) - 1
        return self.gettree(A, left, right)
        
    # 递归  
    def gettree(self, A, left, right):
        if left <= right:
            mid = (left + right) // 2
            root = TreeNode(A[mid])
            root.left = self.gettree(A, left, mid - 1)
            root.right = self.gettree(A, mid + 1, right)
        else:
            return None
        return root
    # 先序遍历
    def view(self,root):
        if root == None:
            return
        print root.val
        self.view(root.left)
        self.view(root.right)

if __name__ == '__main__':
    list1 = [1,2,3,4,5,6,7]
    tree = Solution()
    data = tree.listtotree(list1)
    print tree.view(data)