File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ # Definition for a binary tree node.
2+ from typing import Optional
3+
4+
5+ class TreeNode :
6+ def __init__ (self , val = 0 , left = None , right = None ):
7+ self .val = val
8+ self .left = left
9+ self .right = right
10+
11+
12+ class Solution :
13+ def kthSmallest (self , root : Optional [TreeNode ], k : int ) -> int :
14+ result = []
15+
16+ def inorderTraverse (node : Optional [TreeNode ]):
17+ if node is None or len (result ) >= k :
18+ return
19+
20+ inorderTraverse (node .left )
21+
22+ if len (result ) < k :
23+ result .append (node .val )
24+
25+ inorderTraverse (node .right )
26+
27+ inorderTraverse (root )
28+
29+ return result [k - 1 ]
30+
31+
32+ # Time Complexity: O(N)
33+ # In the worst case, we need to visit all the nodes in the tree.
34+ # Thus, the time complexity is O(N), where N is the number of nodes in the tree.
35+
36+ # Space Complexity: O(N)
37+ # The space complexity is determined by the recursion stack and the result list.
38+ # 1. Recursion stack: In the worst case (unbalanced tree), the recursion stack can go up to N levels deep, so the space complexity is O(N).
39+ # In the best case (balanced tree), the recursion stack depth is log(N), so the space complexity is O(log N).
40+ # 2. Result list: The result list stores up to k elements, so the space complexity is O(k).
You can’t perform that action at this time.
0 commit comments