链接:https://leetcode-cn.com/submissions/detail/73071277/
代码:
/** * 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) return nullptr; if(root->val == p->val || root->val == q->val) return root; TreeNode* lson = lowestCommonAncestor(root->left, p, q); TreeNode* rson = lowestCommonAncestor(root->right, p, q); if(!lson) return rson; if(!rson) return lson; if(lson && rson) return root; return nullptr; } };
代码:递归,只有两个子树都出现 p,q,他们的 root 才是答案。如果左子树没有,则返回右子树,反之亦然,这个是比较难想,可以理解为是为了后序遍历。