# Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition

1.两个节点在某个节点R的同一棵子树上，那么最近公共祖先就是两个节点中深度较浅的节点
2.两个节点在某个节点R的不同子树上，那么最近公共祖先就是R
（节点R一定是满足上述两个条件之一的最深的节点）

LCA可以应用于计算二叉树任意两个节点的最短距离，应用公式$depth_p + depth_q – 2 * depth_{LCA}$（depth表示节点的深度，该公式易得）