Python•lowest-common-ancestor-of-a-binary-search-tree/synced-solution.py
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root
C++•lowest-common-ancestor-of-a-binary-search-tree/synced-solution.cpp
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (root) {
if (p->val < root->val && q->val < root->val) {
root = root->left;
} else if (p->val > root->val && q->val > root->val) {
root = root->right;
} else {
return root;
}
}
return nullptr;
}
};
TypeScript•lowest-common-ancestor-of-a-binary-search-tree/synced-solution.ts
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
while (root) {
if (p!.val < root.val && q!.val < root.val) {
root = root.left;
} else if (p!.val > root.val && q!.val > root.val) {
root = root.right;
} else {
return root;
}
}
return null;
}