题目来源:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
C++题解:弄清思路就好写,理不清思路就唉。。
递归法:
1. 确定函数返回类型和参数:目标是最近公共节点,所以返回类型为TreeNode*,参数为当前节点和两个目标节点。
2. 确定终止条件:遇到空则返回空,遇到q或p节点,则将其返回。
3. 确定单层递归逻辑(重点!):如果左右子树都返回节点,说明当前节点才是公共节点;如果只有左子树返回节点,右子树为空,返回左子树节点,因为右子树为空说明右子树没有目标节点,假设左子树遇到的是目标节点p,那么目标节点q一点为目标节点p的子树节点;其它情况,返回右子树节点,因为如果两子树都为空,就返回空节点。
/**
* 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 == p || root == q || root == NULL) return root;
TreeNode* lefttree = lowestCommonAncestor(root->left, p, q);
TreeNode* righttree = lowestCommonAncestor(root->right, p, q);
if(lefttree && righttree) return root;
else if(lefttree) return lefttree;
else return righttree;
}
};