236. Lowest Common Ancestor of a Binary Tree Posted on 2020-04-10 16:51:00 Edited on 2020-10-11 23:07:40 Disqus: 236. Lowest Common Ancestor of a Binary Tree If we can find two subtrees of root such that both of them has target, then root is the LCA of p and q. If there is exactly one subtree of root having target and root itself has target, then root is the LCA of p and q too. 1234567891011121314151617181920212223242526272829303132/** * 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 *ans; bool hasTarget(TreeNode *root, TreeNode *p, TreeNode *q) { if (root == nullptr) return false; bool left = hasTarget(root->left, p, q); bool right = hasTarget(root->right, p, q); bool mid = root == p || root == q; if ((left && right) || (left && mid) || (mid && right)) { ans = root; } return left || right || mid; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { ans = nullptr; hasTarget(root, p, q); return ans; }}; Post author: ToRapture Post link: https://torapture.github.io/2020/04/10/236-Lowest-Common-Ancestor-of-a-Binary-Tree/ Copyright Notice: All articles in this blog are licensed under BY-NC-SA unless stating additionally.