236. 二叉树的最近公共祖先 - 力扣(LeetCode) (leetcode-cn.com)
二叉树的最近公共祖先
递归
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
else if (!left && right) return right;
else if (left && !right) return left;
else return nullptr;
}
};
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode) (leetcode-cn.com)
二叉搜索树的最近公共祖先
递归
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root->val > p->val && root->val > q->val)
return lowestCommonAncestor(root->left, p, q);
else if (root->val < p->val && root->val < q->val)
return lowestCommonAncestor(root->right, p, q);
else return root;
}
};
非递归
- 自顶向下,我们遇到的第一个值在pq之间的结点就是最近公共祖先。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (root) {
if (root->val > p->val && root->val > q->val) root = root->left;
else if (root->val < p->val && root->val < q->val) root = root->right;
else return root;
}
return nullptr;
}
};
|