首页 > 代码库 > Lowest Common Ancestor of a Binary Tree

Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor of two given nodes in the tree.

 

Node* LCA(Node* root, Node* p, Node* q){    if (root == NULL || p == NULL || q == NULL)        return NULL;    if (root == p || root == q)        return root;    Node* L = LCA(root->left, p, q);    Node* R = LCA(root->right, p, q);    if (L && R)        return root;    else        L ? L : R;}

 

Lowest Common Ancestor of a Binary Tree