GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/python/654_Maximum_Binary_Tree.py at master · qiyuangong/leetcode Expand file tree/ Copy path654_Maximum_Binary_Tree.pyMore file actions 39 lines (36 loc) · 1.26 KB / Copy path654_Maximum_Binary_Tree.pyFile metadata and controls39 lines (36 loc) · 1.26 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ # O (n^2) and O(n) if nums is None or len(nums) == 0: return None max_index, max_value = 0, 0 for i, value in enumerate(nums): if value >= max_value: max_value = value max_index = i root = TreeNode(max_value) root.left = self.constructMaximumBinaryTree(nums[:max_index]) root.right = self.constructMaximumBinaryTree(nums[max_index+1:]) return root # def constructMaximumBinaryTree(self, nums): # # https://leetcode.com/problems/maximum-binary-tree/discuss/106146/C++-O(N)-solution # stack = [] # for value in nums: # curr = TreeNode(value) # while len(stack) != 0 and stack[-1].val < value: # curr.left = stack[-1] # stack.pop() # if (len(stack) != 0): # stack[-1].right = curr # stack.append(curr) # return stack[0] |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |