数据结构练习(36)二叉树两结点的最低共同父结点

http://zhedahht.blog.163.com/blog/static/25411174201081263815813/

思路1:

1. 构建从head到node的path,这个递归的思路需要借鉴。

2. 从2条path中得到公共节点,然后就可以利用以前的方法了。

#include <list>

using namespace std;



struct tree{

    int m_value;

    tree* m_lhs;

    tree* m_rhs;

};



bool GetNodePath(tree* head, tree* node, list<tree*>& path)

{

    if (head == node)

        return true;



    path.push_back(head);



    bool found = false;

    if (head->m_lhs)

        found = GetNodePath(head->m_lhs, node, path);

    if (!found && head->m_rhs)

        found = GetNodePath(head->m_rhs, node, path);



    if (!found)

        path.pop_back();



    return found;

}



tree* LastCommonNode(const list<tree*>& path1, const list<tree*>& path2)

{

    list<tree*>::const_iterator iter1 = path1.begin();

    list<tree*>::const_iterator iter2 = path2.begin();



    tree* lastnode = nullptr;

    

    while (iter1 != path1.end() && iter2 != path2.end())

    {

        if (*iter1 == *iter2)

            lastnode = *iter1;



        ++iter1, ++iter2;

    }

    return lastnode;

}



tree* GetCommonParent(tree* head, tree* node1, tree* node2)

{

    if (head == nullptr || node1 == nullptr || node2 == nullptr)

        return nullptr;



    list<tree*> path1;

    GetNodePath(head, node1, path1);



    list<tree*> path2;

    GetNodePath(head, node2, path2);



    return LastCommonNode(path1, path2);

}

思路2:

也是递归,如果找到node则返回1,找不到则返回0.

TreeNode* lca = NULL;

int traverse(TreeNode* p, TreeNode* p1, TreeNode* p2) {

    if (!p) return 0;

    if (p == p1 || p == p2) return 1;

    int res = traverse(p->m_pLeft, p1, p2) + traverse(p->m_pRight, p1, p2);

    if (res == 2 && lca == NULL) lca = p;

    return res;

}

变型:

如果该树为二叉查找树的话,就要稍微变换下思路了。

如果2个节点的值都小于根节点,则在其左边,否则在右边。

 

你可能感兴趣的:(数据结构)