Topic describes

Their thinking

  • Use the traversal idea of DFS to traverse binary trees
  • If it is empty or p or Q, the node is returned directly
  • If p and q are both present, the current root node is returned. If only one is present, the non-empty node is returned.

The implementation code

var lowestCommonAncestor = function(root, p, q) {
    if (root === null || root === p || root === q) {
        return root;
    }

    let x = lowestCommonAncestor(root.left,p,q);
    let y = lowestCommonAncestor(root.right,p,q);

    if (x && y) {
        return root;
    } else {
        return x || y;   // Return the existing one}};Copy the code