def createBtree(self): root = TreeNode(3) root.left = TreeNode(9) subBranch = TreeNode(20) subBranch.left = TreeNode(15) subBranch.right = TreeNode(7) root.right = subBranch return root
def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ node = head if node is None: return None if node.next is None: return TreeNode(node.val) # transfer linked list to array array_whole = [node.val] while node.next: node = node.next array_whole.append(node.val) mid = int(len(array_whole) / 2) root = TreeNode(array_whole[mid]) # split the array array_l = array_whole[:mid] array_r = [] if mid == len(array_whole) - 1 else array_whole[mid + 1:] # processing left if len(array_l) > 0: node = ListNode(array_l.pop(0)) head_l = node while array_l: node.next = ListNode(array_l.pop(0)) node = node.next root.left = self.sortedListToBST(head_l) else: root.left = None # processing right if len(array_r) > 0: node = ListNode(array_r.pop(0)) head_r = node while array_r: node.next = ListNode(array_r.pop(0)) node = node.next root.right = self.sortedListToBST(head_r) else: root.right = None return root
def testCase2(self): root = TreeNode(-10) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) return root
def testCase3(self): root = TreeNode(1) root.left = TreeNode(2) root.left.left = TreeNode(2) root.left.right = TreeNode(3) root.right = TreeNode(4) return root
def testCase4(self): root = TreeNode(-5) root.left = TreeNode(2) root.right = TreeNode(3) root.right.left = TreeNode(-1) root.right.right = TreeNode(4) return root
def constructCase(self): from customDataType import TreeNode root = TreeNode(4) root.left = TreeNode(9) root.right = TreeNode(0) root.left.left = TreeNode(5) root.left.right = TreeNode(1) root.left.left.left = TreeNode(8) return root
def testCase(self): root = TreeNode(3) root.left = TreeNode(9) # root.left.right = TreeNode(4) root.left.left = TreeNode(15) # root.left.left.left = TreeNode(7) root.right = TreeNode(20) # root.right.left = TreeNode(15) # root.right.right = TreeNode(7) return root
def constructCase2(self): from customDataType import TreeNode root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) # root.left.right = TreeNode(3) # root.right.left = TreeNode(6) root.right.right = TreeNode(9) return root
def testCase(self): root = TreeNode(5) root.left = TreeNode(4) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) root.right = TreeNode(8) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) return root, 22
def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ L = len(nums) if L == 0: return None m = int(L / 2) node = TreeNode(nums[m]) node.left = self.sortedArrayToBST(nums[:m]) node.right = self.sortedArrayToBST(nums[m + 1:]) return node