LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
原题链接
简单
作者:
JasonSun
,
2020-08-17 12:14:50
,
所有人可见
,
阅读 413
Tree Fold
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
std::function<TreeNode*(TreeNode*)> fold = [&](TreeNode* node) {
if (std::min(p->val, q->val) <= node->val and std::max(p->val, q->val) >= node->val) {
return node;
}
else if (node->val < std::min(p->val, q->val)) {
return fold(node->right);
}
else {
return fold(node->left);
}
};
return fold(root);
}
};