二叉树中任意两个节点间的距离 源码

来源:互联网 发布:ssh 指定端口登陆 编辑:程序博客网 时间:2024/06/17 16:11
#include <iostream>#include <list>template<typename T> struct BNode {    BNode(T d) {        data = d;        left = NULL;        right = NULL;    }    void visit() {        std::cout << data << std::endl;    }    T data;    BNode<T> *left;    BNode<T> *right;};// 获取访问路径template<typename T> std::list<BNode<T>*>* getPath(BNode<T> *root, BNode<T> *node) {    if (root && node) {        std::list<BNode<T>*> *pList = new std::list<BNode<T>*>();        for (BNode<T> *iter = root; !pList->empty() || iter != NULL;) {            while (iter) {                pList->push_back(iter);                if (iter == node) {                    return pList;                }                iter = iter->left;            }            while (!pList->empty() && iter == pList->back()->right) {                iter = pList->back();                pList->pop_back();            }            if (!pList->empty()) {                iter = pList->back()->right;            }        }    }    return NULL;}// 计算任意两个节点间的距离template<typename T> int distance(BNode<T> *root, BNode<T> *node1, BNode<T> *node2) {    if (root && node1 && node2) {        std::list<BNode<T>*> *pList1 = getPath<T>(root, node1);        std::list<BNode<T>*> *pList2 = getPath<T>(root, node2);        while (pList1->front() == pList2->front()) {            pList1->pop_front();            pList2->pop_front();        }        size_t len = pList1->size() + pList2->size();        delete pList1;        delete pList2;        return len;    }    return 0;}// 测试代码int main() {    typedef BNode<char> BCharNode;    BCharNode root('A');    BCharNode nodeB('B');    BCharNode nodeD('D');    BCharNode nodeE('E');    nodeB.left = &nodeD;    nodeB.right = &nodeE;    BCharNode nodeC('C');    BCharNode nodeF('F');    BCharNode nodeG('G');    nodeC.left = &nodeF;    nodeC.right = &nodeG;    root.left = &nodeB;    root.right = &nodeC;    /*std::list<BCharNode*>* pList = getPath<char>(&root, &nodeF);     for (std::list<BCharNode*>::iterator iter = pList->begin(); iter != pList->end(); ++iter) {     (*iter)->visit();     }     delete pList;*/    std::cout << distance<char>(&root, &nodeF, &nodeG) << std::endl;    return 0;}

原创粉丝点击