二叉树的最近公共祖先
题目链接:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
思路:构造递归判断节点是否在子树的辅助函数,然后主函数递归:
- 若root就是其中一个节点,返回root
- 若两个节点分别在root的左右子树,返回root
- 若两个节点在root的同一侧,root赋值为该子树root,重复该过程
参考代码:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (root != NULL) {
if (root->val == p->val || root->val == q->val) {
return root;
}
if (isInSubTree(root->left, p)) {
if (isInSubTree(root->left, q)) {
root = root->left;
continue;
}
else {
return root;
}
}
else if (isInSubTree(root->right, p)) {
if (isInSubTree(root->right, q)) {
root = root->right;
continue;
}
else {
return root;
}
}
}
return root;
}
bool isInSubTree(TreeNode* root, TreeNode* n) {
if (root == NULL) {
return false;
}
if (root->val == n->val) {
return true;
}
return isInSubTree(root->left, n) || isInSubTree(root->right, n);
}
};