2026/05/18

[LeetCode] 236 Lowest Common Ancestor of a Binary Tree

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * 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 {
private:
  TreeNode *LCABT(TreeNode *cur, TreeNode *p, TreeNode *q) {
    if (!cur || cur == p || cur == q)
      return cur;
    TreeNode *left = LCABT(cur->left, p, q);
    TreeNode *right = LCABT(cur->right, p, q);
    if (left && right)
      return cur;
    if (left)
      return left;
    return right;
  }

public:
  TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
    return LCABT(root, p, q);
  }
};