diff --git a/kth-smallest-element-in-a-bst/ppxyn1.py b/kth-smallest-element-in-a-bst/ppxyn1.py new file mode 100644 index 0000000000..0baf399124 --- /dev/null +++ b/kth-smallest-element-in-a-bst/ppxyn1.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +#idea : DFS (inorder) +#Time Complexity: O(n) + +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + stack = [] + cnt = 0 + curr = root + if not curr: + return + + while curr or stack: + while curr: + stack.append(curr) + curr = curr.left + curr = stack.pop() + cnt += 1 + + if cnt == k: + return curr.val + + curr = curr.right + diff --git a/lowest-common-ancestor-of-a-binary-search-tree/ppxyn1.py b/lowest-common-ancestor-of-a-binary-search-tree/ppxyn1.py new file mode 100644 index 0000000000..7357bdeab4 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/ppxyn1.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +# idea: BST property +# Time Complexity : O(long n) +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + cur = root + while cur: + if p.val > cur.val and q.val > cur.val: + cur = cur.right + elif p.val < cur.val and q.val < cur.val: + cur = cur.left + else: + return cur + + + +