LeetCode - 236. 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]
就是求二叉树中两个节点的公共祖先节点(节点自身可以是自己的祖先节点),比如上图中,5 号节点和 1 号节点的公共祖先节点就是 3 号节点,5 号节点和 4 号节点的公共祖先节点就是 5 号节点自身。
由于自己可以是自己的祖先节点(假设我们找 a 和 b 两个节点的最低公共祖先节点),所以当我们找到一个节点 Root 的左节点是 a,那么只需要在 Root 的另一边找 b 就好了,如果找到了,那么公共祖先节点为 Root,如果没有找到,那么最低公共祖先节点就是 a 节点。
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return root;
if(root == p || root == q) return root;
auto l = lowestCommonAncestor(root->left, p, q);
auto r = lowestCommonAncestor(root->right, p, q);
if(l && r)
return root;
return l ? l : r;
}