/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr) {
return root;
}
if(root == p || root == q) {
return root;
}
TreeNode *left = lowestCommonAncestor(root->left,p,q);
TreeNode *right = lowestCommonAncestor(root->right,p,q);
if(left != nullptr && right != nullptr) {
return root;
}
if(left == nullptr) {
return right;
}
return left
}
};
【二叉树】【递归】剑指 Offer 68 - II. 二叉树的最近公共祖先
最新推荐文章于 2022-10-20 20:31:02 发布