解决思路:
利用递归:递归函数lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)的作用是找到以root为根节点的二叉树,p和q的最近公共祖先;
其他的解决方法可以利用map保存节点和父节点的映射,不过需要额外的空间。
/**
* 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 || root == p || root == q) { //如果在寻找的过程中找到了p和q节点,直接返回
return root;
}
TreeNode *left = lowestCommonAncestor(root->left, p, q); // 从root的左子树中寻找最近祖先
TreeNode *right = lowestCommonAncestor(root->right, p, q); // 从root的右子树中寻找最近祖先
if(left == nullptr && right == nullptr) // 如果p和q都不存在,返回nullptr
return nullptr;
if(left != nullptr && right != nullptr) //如果两个节点都在 左子树和右子树中,说明节点p和节点q在以root为根节点的树中。
return root;
return left == nullptr ? right : left; // 返回非空的节点
}
};