Find LCA in a binary tree

1 min read

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

class Solution {
public:
  TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
    if (root == nullptr) {
      return root;
    }

    if (root == p || root == q) {
      return root;
    }

    TreeNode *lt = lowestCommonAncestor(root->left, p, q);
    TreeNode *rt = lowestCommonAncestor(root->right, p, q);

    if (lt && rt) {
      return root;
    } else {
      return lt ? lt : rt;
    }
  }
};
Print all K sum paths in a binary tree
Find distance between 2 nodes in a binary tree