题目链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
思路如下:
lowestCommonAncestor
函数就是在以 root 为根节点的二叉树中查找 p、q 的最近公共祖先。
- 如果这棵树中的某个节点就是节点 p 或者 q,那么就向上返回这个节点给父节点;
- 如果当前节点的左右子树返回值分别是 p、q,那么当前这个节点就是最近公共祖先;
- 如果当前节点只有一个子树的返回值为 p 或 q 节点,则返回该值;
- 如果当前节点的两个子树返回值都为空,则返回空指针。
C++代码如下:
/**
* 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) {
// 如果当前节点为空或者当前节点就是p或者当前节点就是q,那么就返回当前节点给父节点
if (root == nullptr || root == p || root == q) return root;
// 递归遍历左子树
auto left = lowestCommonAncestor(root->left, p, q);
// 递归遍历右子树
auto right = lowestCommonAncestor(root->right, p, q);
// 如果left、right都不为空,那么代表p、q在当前节点的两侧,所以当前节点就是最近公共祖先
if (left != nullptr && right != nullptr) return root;
// 如果left、right有一个为空,那么就返回不为空的那一个
return (left != nullptr) ? left : right;
}
};
学习心得:要想用好递归,得从宏观上思考递归函数干了什么、返回什么,不要过分扣递归的底层细节。
参考链接:https://blog.nowcoder.net/n/4fb0aa54d2a449a89d7183477c609687