Strategy: Idea is to keep a counter in the #logic area of inorder traversal and the moment it reaches target(depending you're decrementing to 1 or incremting to k) you can start returning the node.val. Regular inorder, Basic idea is to Go left, decrement k, Go right At any stage if k == 1, meaning we found our target keep returning that val back. If there are multiple insertion/deletion of nodes and we need to calculate kthsmallest frequently, we should start storing count of nodes in left subtree at every nodes, which can easiliy be maintained while creation/deletion and easy to access too. Time: O(max(h,k)) Space: O(h) https://discuss.leetcode.com/topic/17810/3-ways-implemented-in-java-python-binary-search-in-order-iterative-recursive/75 """ self.k = k return self.inorder(root) if __name__ == '__main__': from tree_base import level_order_array_to_tree arr = [4, 2, 6, 1, 3, 5, 7] # arr = [1] # arr = [3, 2, None] # arr = [3, None, 4] root, k = level_order_array_to_tree(arr), 2 sol = Solution() print sol.k_smallest_optimized_recursive(root, k)
# trick is to use stack, which recursion uses also. from tree_base import Node stack = [root] tos = None in_order = [] while(stack or tos is not None): if tos is None: tos = stack.pop() if not isinstance(tos, Node): in_order.append(tos) try: tos = stack.pop() except IndexError: tos = None continue if tos.right is not None: stack.append(tos.right) stack.append(tos.val) tos = tos.left return in_order if __name__ == '__main__': from tree_base import level_order_array_to_tree # arr = [1, None, 2, None, None, 3, None] # arr = ['A', 'B', 'C', 'D', "E", "F", "G"] # arr = ['A', 'B', 'C'] arr = ['a', 'b'] root = level_order_array_to_tree(arr) print inorder_iteration(root)
""" def are_identical(root1, root2): if root1 is None or root2 is None: if root1 != root2: return False else: return True if root1.val != root2.val: return False if not are_identical(root1.left, root2.left): return False if not are_identical(root1.right, root2.right): return False return True if __name__ == '__main__': from tree_base import level_order_array_to_tree # arr1, arr2 = [1, 2, 3], [1, 2, 3] # arr1, arr2 = [1, 2, 3], [1, None, 2, None, 3] # arr1, arr2 = [1, 2, None], [1, None, 2] # arr1, arr2 = [1, 2, 3], [1, 3, 2] # arr1, arr2 = [4, 2, 3], [1, 2, 3] # arr1, arr2 = [1, 2, 3], [1, 2, None] arr1, arr2 = [1], [1] root1 = level_order_array_to_tree(arr1) root2 = level_order_array_to_tree(arr2) print are_identical(root1, root2)