题目描述
Leetcode : 235. Lowest Common Ancestor of a Binary Search Tree
Leetcode : 236. Lowest Common Ancestor of a Binary Tree
解题思路
AC代码
//leetcode 235
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr)
return root;
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;
}
};
//leetcode 236
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==nullptr)
return root;
if(root->val == p->val || root->val == q->val)
return root;
TreeNode* leftNode = lowestCommonAncestor(root->left, p, q);
TreeNode* rightNode = lowestCommonAncestor(root->right, p, q);
if(leftNode && rightNode)
return root;
return leftNode?leftNode:rightNode?rightNode:nullptr;
}
};
|