My Solution to Lowest Common Ancestor of a Binary Tree Part I(Bottomup Approach)

题目:

http://www.leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html

#include <iostream>
using namespace std;

struct Node{
    int value;
    Node *pLeft;
    Node *pRight;
};

Node *CreateNode(int v)
{
    Node *pNode = new Node();
    if (!pNode)
        return NULL;

    pNode->value = v;
    pNode->pLeft = NULL;
    pNode->pRight = NULL;

    return pNode;
}

void LinkNode(Node *root, Node *pLeftChildNode, Node *pRightChildNode)
{
    root->pLeft = pLeftChildNode;
    root->pRight = pRightChildNode;
}

Node *LCA(Node *root, Node *p, Node *q)
{
    if (!root || !p || !q)        // 如果是叶子节点的空孩子,那么返回NULL
        return NULL;

    if (root == p || root == q)    // 如果当前节点是p或者q,那么返回当前节点(这还不是LCA,上层的LCA节点会返回LCA自己的)
        return root;

    // 以下包括好几层意思:
    // 1、如果a b都存在,那么说明p q在不同的子树中,说明是LCA,可以返回root了
    // 2、如果a b都是NULL,说明root的子树里没有p q,那么返回NULL
    // 3、如果a b仅一个存在,那么就向上返回这仅有的一个(这个有可能是LCA,也有可能不是):
    //    如果这个是LCA,那么 return a ? a : b; 会一直向上返回,直到root;
    //    如果这个还不是LCA,那么向上返回直到上层的LCA发现另一棵子树含有另一个节点(逻辑1)
    Node *a = LCA(root->pLeft, p, q);
    Node *b = LCA(root->pRight, p, q);
    if (a && b)
        return root;

    return a ? a : b;
}

int main()
{
    Node *p[8];
    p[0] = CreateNode(3);
    p[1] = CreateNode(5);
    p[2] = CreateNode(1);
    p[3] = CreateNode(6);
    p[4] = CreateNode(2);
    p[5] = CreateNode(0);
    p[6] = CreateNode(8);
    p[7] = CreateNode(7);
    p[8] = CreateNode(4);

    if (!p[0] || !p[1] || !p[2] || !p[3] || !p[4] || !p[5] || !p[6] || !p[7] || !p[8])
    {
        cout<<"Create Node Err!"<<endl;
        return -1;
    }

    LinkNode(p[0], p[1], p[2]);
    LinkNode(p[1], p[3], p[4]);
    LinkNode(p[2], p[5], p[6]);
    LinkNode(p[4], p[7], p[8]);
    
    Node *pLCA = LCA(p[0], p[0], p[2]);
    Node *pLCA2 = LCA(p[0], NULL, NULL);

    if (pLCA)
        cout<<"pLCA->value = "<<pLCA->value<<endl;
    else
        cout<<"Error"<<endl;

    if (pLCA2)
        cout<<"pLCA2->value = "<<pLCA2->value<<endl;
    else
        cout<<"Error"<<endl;

    return 0;
}

end

原文地址:https://www.cnblogs.com/lihaozy/p/2799849.html