def recursive(self, l, r) -> TreeNode: m = (l + r) // 2 root = TreeNode(self.nums[m]) if m > l: root.left = self.recursive(l, m) if m < r - 1: root.right = self.recursive(m + 1, r) return root
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return TreeNode(val) if root.val > val: root.left = self.insertIntoBST(root.left, val) else: root.right = self.insertIntoBST(root.right, val) return root
def recursive(self, preorder: List[int], inorder: List[int]) -> TreeNode: v = preorder[0] i = inorder.index(v) root = TreeNode(v) if i > 0: root.left = self.recursive(preorder[1:(1 + i)], inorder[:i]) if i < len(inorder) - 1: root.right = self.recursive(preorder[(i + 1):], inorder[(i + 1):]) return root
def recursive(self, x): n = len(x) i = n // 2 node = TreeNode(x[i]) if n > 1: node.left = self.recursive(x[:i]) if n > 2: node.right = self.recursive(x[(i + 1):]) return node
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode: # Q0654. if not root or root.val < val: node = TreeNode(val) node.left = root return node else: root.right = self.insertIntoMaxTree(root.right, val) return root
def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: if not pre: return None root = TreeNode(pre[0]) if len(pre) == 1: return root i = post.index(pre[1]) + 1 root.left = self.constructFromPrePost(pre[1:(i + 1)], post[:i]) root.right = self.constructFromPrePost(pre[i + 1:], post[i:-1]) return root
def recursive(self, pre, post): node = TreeNode(pre[0]) # i is the index on post matches pre[1] # pre[1] is the root of the left subtree i = len(post) - 2 while i > -1 and not pre[1] == post[i]: i -= 1 if i >= 0: node.left = self.recursive(pre[1:(i + 2)], post[:(i + 1)]) if i < len(post) - 2: node.right = self.recursive(pre[(i + 2):], post[(i + 1):-1]) return node
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t1 and t2: t = TreeNode(t1.val + t2.val) t.left = self.mergeTrees(t1.left, t2.left) t.right = self.mergeTrees(t1.right, t2.right) elif t1: t = t1 elif t2: t = t2 else: t = None return t
def recursive(self, l, r) -> TreeNode: """Args: l, r: sub-inorder formed from self.inorder[l:r], l < r """ v = self.preorder[self.preindex] i = self.inorder[v] self.preindex += 1 root = TreeNode(v) if i > l: root.left = self.recursive(l, i) if i < r - 1: root.right = self.recursive(i + 1, r) return root
def allPossibleFBT(self, N: int) -> List[TreeNode]: if N & 1: if N not in self.memo: self.memo[N] = [] for i in range(1, N, 2): for x in self.allPossibleFBT(i): for y in self.allPossibleFBT(N - 1 - i): node = TreeNode(0) node.left = x node.right = y self.memo[N].append(node) return self.memo[N] return []
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: # preorder traversal, assign depth root.depth = 0 stack, dmax, dmaxNodes = [root], 0, {root} while stack: node = stack.pop() if node.right: node.right.parent = node node.right.depth = node.depth + 1 if node.right.depth > dmax: dmax = node.right.depth dmaxNodes = {node.right} elif node.right.depth == dmax: dmaxNodes.add(node.right) stack.append(node.right) if node.left: node.left.parent = node node.left.depth = node.depth + 1 if node.left.depth > dmax: dmax = node.left.depth dmaxNodes = {node.left} elif node.left.depth == dmax: dmaxNodes.add(node.left) stack.append(node.left) # climb back to common ancestor while len(dmaxNodes) > 1: dmaxNodes = set(node.parent for node in dmaxNodes) return dmaxNodes.pop()
def bstFromPreorder(self, preorder: List[int]) -> TreeNode: n = len(preorder) if not n: return None root = TreeNode(preorder[0]) stack = [root] for i in range(1, n): node, child = stack[-1], TreeNode(preorder[i]) while stack and stack[-1].val < child.val: node = stack.pop() if node.val > child.val: node.left = child else: node.right = child stack.append(child) return root
def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]: if root and voyage: if root.val == voyage[0]: if root.left and root.right: X = [] if root.left.val == voyage[1]: pass elif root.right.val == voyage[1]: root.left, root.right = root.right, root.left X = [root.val] else: return [-1] try: i = voyage.index(root.right.val) L = self.flipMatchVoyage(root.left, voyage[1:i]) if L == [-1]: return [-1] R = self.flipMatchVoyage(root.right, voyage[i:]) if R == [-1]: return [-1] return X + L + R except ValueError as identifier: return [-1] elif root.left: return self.flipMatchVoyage(root.left, voyage[1:]) elif root.right: return self.flipMatchVoyage(root.right, voyage[1:]) else: return [] else: return [-1]
def minCameraCover(self, root: TreeNode) -> int: self.count = 0 self.recursive(root) if root.val == root.mnt == 0: root.val = 1 self.count += 1 return self.count
def splitBST(self, root: TreeNode, V: int) -> List[TreeNode]: if not root: return None, None elif root.val > V: node, root.left = self.splitBST(root.left, V) return node, root else: root.right, node = self.splitBST(root.right, V) return root, node
def recursive(self, i): if i == self.n: return None, self.n v = "" while i < self.n and not (self.s[i] == "(" or self.s[i] == ")"): v += self.s[i] i += 1 node = TreeNode(int(v)) if i < self.n and self.s[i] == "(": node.left, i = self.recursive(i + 1) if i < self.n and self.s[i] == "(": node.right, i = self.recursive(i + 1) if i < self.n and self.s[i] == ")": i += 1 elif i < self.n and self.s[i] == ")": i += 1 elif i < self.n and self.s[i] == ")": i += 1 return node, i
def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. """ x = deque([int(v) for v in data.split()]) if not x: return None root = TreeNode(x.popleft()) # decode w.r.t bst property stack = [root] while x: node = TreeNode(x.popleft()) if node.val < stack[-1].val: stack[-1].left = node else: while stack and node.val > stack[-1].val: hold = stack.pop() hold.right = node stack.append(node) return root
def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree. """ x = deque(data.split(',')) v = x.popleft() if v == "" or v == " ": return None root = TreeNode(v) stack = deque([root, ]) while x: node = stack.popleft() v = x.popleft() if not v == " ": node.left = TreeNode(v) stack.append(node.left) if x: v = x.popleft() if not v == " ": node.right = TreeNode(v) stack.append(node.right) return root
def preorderListToTreeNode(self, x: List) -> TreeNode: """preorder representation of tree as list with none back to root (TreeNode), copied from ./config/treenode.py """ if not x: return None root = TreeNode(x[0]) i, q = 1, [ [root, True], ] while i < len(x): node, ld = q[-1] item = x[i] if ld: q[-1][1] = False if item is not None: node.left = TreeNode(item) q.append([node.left, True]) else: q.pop() if item is not None: node.right = TreeNode(item) q.append([node.right, True]) i += 1 return root
def insert(self, v: int) -> int: # create and connect node = TreeNode(v) if self.q[0][0]: self.q[0][1].right = node else: self.q[0][1].left = node x = self.q[0][1].val # pop if complete self.q[0][0] += 1 if self.q[0][0] == 2: self.q.popleft() # append new node self.q.append([0, node]) return x
def recoverFromPreorder(self, S: str) -> TreeNode: stack, i = [], 0 while i < len(S): d, x = 0, '' while i < len(S) and S[i] == '-': d += 1 i += 1 while i < len(S) and S[i] != '-': x += S[i] i += 1 while len(stack) > d: stack.pop() node = TreeNode(x) if stack and stack[-1].left is None: stack[-1].left = node elif stack: stack[-1].right = node stack.append(node) return stack[0]
def simulateInorderTraversal(self, l, r) -> TreeNode: if l == r - 1: node = TreeNode(self.head.val) self.head = self.head.next return node m = (l + r) // 2 if m > l: hold = self.simulateInorderTraversal(l, m) node = TreeNode(self.head.val) self.head = self.head.next node.left = hold if m < r - 1: node.right = self.simulateInorderTraversal(m + 1, r) return node
def treeToDoublyList(self, root: TreeNode) -> TreeNode: # sentinel s = TreeNode('') # inorder traversal x = s if root: node, stack = root, [] while node or stack: while node: stack.append(node) node = node.left # next smallest node = stack.pop() # create the double link in-place x.right = node node.left = x # move along the path of double linked list x = node # move along the path of tree inorder traversal node = node.right # complete the circle x.right = s.right s.right.left = x return s.right # if __name__ == '__main__': # solver = Solution() # cases = [ # [], # [1], # [2,1,3], # [4,2,5,1,3], # ] # cases = [ # listToTreeNode(x) for x in cases # ] # rslts = [ # solver.treeToDoublyList(root) for root in cases # ] # for cs, rs in zip(cases, rslts): # print(f"case:\n{cs.display() if cs else None} | solution: {rs}")
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode: if d == 1: node = TreeNode(v) node.left = root return node # level order traversal if root: level, stack = 0, [root] while stack: level, queue = level + 1, [] if level == d - 1: for node in stack: xl, xr = TreeNode(v), TreeNode(v) xl.left, xr.right = node.left, node.right node.left, node.right = xl, xr break else: for node in stack: if node.left: queue.append(node.left) if node.right: queue.append(node.right) stack = queue return root
def deleteNode(self, root: TreeNode, key: int) -> TreeNode: if not root: return None if root.val > key: root.left = self.deleteNode(root.left, key) elif root.val < key: root.right = self.deleteNode(root.right, key) else: if root.left: root.val = self.predcessor(root) root.left = self.deleteNode(root.left, root.val) elif root.right: root.val = self.successor(root) root.right = self.deleteNode(root.right, root.val) else: root = None return root
def recoverFromPreorder(self, S: str) -> TreeNode: stack, i, n, d, x = [], 0, len(S), 0, '' while i < n: while S[i] == '-': d += 1 i += 1 while i < n and S[i].isdigit(): x += S[i] i += 1 node = TreeNode(int(x)) if d == 0: root = node stack.append((d, node)) else: while stack and stack[-1][0] >= d: stack.pop() if not stack[-1][1].left: stack[-1][1].left = node else: stack[-1][1].right = node stack.pop() stack.append((d, node)) d, x = 0, '' return root
def __init__(self): self.memo = {} self.memo[1] = [TreeNode(0)]