https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

1. Use recursion:

  1. // 16 ms 14.4 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  14. if (!root || root == p || root == q) return root;
  15. TreeNode* l = lowestCommonAncestor(root->left, p, q);
  16. TreeNode* r = lowestCommonAncestor(root->right, p, q);
  17. if (l && r) return root;
  18. if(l)
  19. return l;
  20. else
  21. return r;
  22. }
  23. };