You can also perform iterative inorder traversal and improve the time complexity to O(H + K). For a balanced tree H = logN however, for a skewed tree, it can be H = N.
O(H + K)
H = logN
H = N
def kthSmallest(root, k): s = [] # stack while root != None or s: while root != None: s.append(root) root = root.left root = s[-1] s.pop() k -= 1 if k == 0: return root.val root = root.right
Thanks for sharing :)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You can also perform iterative inorder traversal and improve the time complexity to
O(H + K)
. For a balanced treeH = logN
however, for a skewed tree, it can beH = N
.Thanks for sharing :)