for i in range(len(nums)): if i in visited: continue path.append(nums[i]) visited.add(i) self.dfs(nums, path, result, visited) visited.remove(i) path.pop()
defiterative_inorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append(it) it = it.left while stack: node = stack.pop() res.append(node.val) if node.right: n = node.right while n: stack.append(n) n = n.left return res
defiterative_preorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append(it) res.append(it.val) it = it.left while stack: node = stack.pop() if node.right: n = node.right while n: stack.append(n) res.append(n.val) n = n.left return res
defiterative_postorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append((it, 0)) # count for it in the stack top it = it.left while stack: pair = stack.pop() node = pair[0] occurrence = pair[1] + 1 if occurrence == 2: res.append(node.val) continue# don't iterate on right node again else: stack.append((node, occurrence)) if node.right: n = node.right while n: stack.append((n, 0)) n = n.left return res
defclosestKValues(self, root: TreeNode, target: float, k: int) -> List[int]: predecessors, successors = [], [] it = root while it: if target < it.val: successors.append(it) it = it.left else: predecessors.append(it) it = it.right res = [] while k > 0: if predecessors and (not successors or target - predecessors[-1].val < successors[-1].val - target): node = predecessors.pop() if node.left: n = node.left while n: predecessors.append(n) n = n.right res.append(node.val) else: node = successors.pop() if node.right: n = node.right while n: successors.append(n) n = n.left res.append(node.val) k -= 1 return res
next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.