Definition for a binary tree node.
Solved at: 220925. Took 17m 09s
Question
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to thedefinition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodespandqas the lowest node inTthat has bothpandqas descendants (where we allowa node to be a descendant of itself)."
Solution
I misunderstood LCA as being the minimum in value.
Results
Runtime
- 89 ms, faster than 86.27% of Python3 online submissions for the Lowest Common Ancestor of a Binary Search Tree.
Memory Usage
- 18.9 MB, less than 23.33% of Python3 online submissions for the Lowest Common Ancestor of a Binary Search Tree.
Improvements
I ignored that this is a Binary Search Tree, not just Binary Tree. Therefore one can binary search to reduce the search scope.
Complexity Analysis
For this, It will be where is the count of the nodes. Space complexity will be for constructing lists and dictionaries.
If we use the above improvement, space complexity will reduce to . However, time complexity will not change.