File tree Expand file tree Collapse file tree 3 files changed +50
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 3 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
3
+ dp = [[] for i in range (target + 1 )]
4
+ dp [0 ] = [[]]
5
+
6
+ for num in candidates :
7
+ for i in range (num , target + 1 ):
8
+ for comb in dp [i - num ]:
9
+ dp [i ].append (comb + [num ])
10
+
11
+ return dp [target ]
12
+
13
+ ## TC: O(outer loop * 1st inner(target size) * 2nd inner(combination #))
14
+ ## SC: O(target size * combination #)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def buildTree (self , preorder : List [int ], inorder : List [int ]) -> Optional [TreeNode ]:
3
+ if len (inorder ) == 0 :
4
+ return None
5
+
6
+ if len (preorder ) == 1 :
7
+ return TreeNode (preorder [0 ])
8
+
9
+ idx = inorder .index (preorder .pop (0 ))
10
+ node = TreeNode (inorder [idx ])
11
+
12
+ node .left = self .buildTree (preorder , inorder [:idx ])
13
+ node .right = self .buildTree (preorder , inorder [idx + 1 :])
14
+
15
+ return node
16
+
17
+
18
+ ## TC: O(n^2), SC: O(n)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def kthSmallest (self , root : Optional [TreeNode ], k : int ) -> int :
3
+ ans = []
4
+
5
+ def helper (node ):
6
+ if not node : return
7
+ helper (node .left )
8
+
9
+ if len (ans ) == k :
10
+ return
11
+
12
+ ans .append (node .val )
13
+ helper (node .right )
14
+
15
+ helper (root )
16
+ return ans [- 1 ]
17
+
18
+ ## TC: O(n), SC: O(h+n) where h == heights(tree) and n == element(tree)
You can’t perform that action at this time.
0 commit comments