代码改变世界

Lowest Common Ancestor of a Binary Tree

2014-12-17 00:00  李涛的技术博客  阅读(112)  评论(0编辑  收藏  举报

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;
}