My Solution to Lowest Common Ancestor of a Binary Tree Part I(Top-Down Approach)

题目在:

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

 

自己将上述网址中的 Top-Down Approach 重写了一遍,为了练手。

这个方法是基础的方法,复杂度为O(n2),简而言之就是先判断p q是在不同的子树还是相同的子树里,如果不同,那么root就是LCA,如果相同,那么递归。

代码如下:

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

bool Contain(Node *root, Node *pNode)        //这种简单的递归是面试的最基础的题,一定要牢牢掌握,一般O(n2)的算法都是基于此类pattern的
{
    if (!root || !pNode)
        return false;

    if (root->value == pNode->value)
        return true;
    else
        return (Contain(root->pLeft, pNode) || Contain(root->pRight, pNode));
}

Node *LCA(Node *root, Node *p, Node *q)
{
    if (!root || !p || !q)
        return NULL;            //通常这个return NULL;都是包括2个含义:1非法输入 2叶子节点或者递归的终止条件

    if (!Contain(root, p) || !Contain(root, q))
        return NULL;

    //如果root等于p或者q,那么root就是LCA
    if (root == p || root == q)
        return root;

    //如果p q不属于root的同一颗子树
    if ( (Contain(root->pLeft, p) && Contain(root->pRight, q)) || 
        (Contain(root->pLeft, q) && Contain(root->pRight, p)) )    //注意这里是root->pLeft和root->pRight
        return root;

    //如果p q都在左子树
    else if (Contain(root->pLeft, p) && Contain(root->pLeft, q))
        return LCA(root->pLeft, p, q);

    //如果p q都在右子树
    else if (Contain(root->pRight, p) && Contain(root->pRight, q))
        return LCA(root->pRight, p, q);
}

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

你可能感兴趣的:(binary)