Esempio n. 1
0
 def sortedArrayToBST(self, nums):
     """
     :type nums: List[int]
     :rtype: TreeNode
     """
     if not nums:
         return None
     mid = (len(nums) - 1) >> 1
     root = TreeNode(nums[mid])
     root.left = self.sortedArrayToBST(nums[:mid])
     root.right = self.sortedArrayToBST(nums[mid + 1:])
     return root
Esempio n. 2
0
 def reConstructBinaryTree2(self, tin, post):
     """根据中序遍历序列和后序遍历序列构建二叉树"""
     if len(tin) == 0 or len(post) == 0:
         return None
     if len(tin) == 1:
         return TreeNode(tin[0])
     else:
         flag = TreeNode(post[-1])
         index = tin.index(post[-1])
         flag.left = self.reConstructBinaryTree2(tin[:index], post[:index])
         flag.right = self.reConstructBinaryTree2(tin[index + 1:],
                                                  post[index:-1])
     return flag
Esempio n. 3
0
 def reConstructBinaryTree1(self, pre, tin):
     """根据先序遍历序列和中序遍历序列构建二叉树"""
     if len(pre) == 0 or len(tin) == 0:
         return None
     if len(pre) == 1:
         return TreeNode(pre[0])
     else:
         flag = TreeNode(pre[0])
         index = tin.index(pre[0])
         flag.left = self.reConstructBinaryTree1(pre[1:index + 1],
                                                 tin[:index])
         flag.right = self.reConstructBinaryTree1(pre[index + 1:],
                                                  tin[index + 1:])
     return flag