树的某节点的所有父节点

来源:互联网 发布:php websocket教程 编辑:程序博客网 时间:2024/05/17 15:21
http://blog.csdn.net/yhmhappy2006/article/details/1566865定位一个节点递归实现为:node FindNode(const node root,int val){       node n = root;       if (NULL == n)              return NULL;        if (n->_value == val)              return n;        node p = FindNode(n->_lchild,val);       if (NULL == p)              return FindNode(n->_rchild,val);       else              return p;}

输出到当前节点的所有路径,也就是当前节点的所有父亲节点集合(这个很有用的,呵呵,知道的人自然知道:))。这个实现其实是根据中序遍历得到的,采用中序遍历的方式查找节点,当查找到当前节点的时候堆栈中保存的就是当前节点以及当前节点的所有父亲节点。实现代码为:


int* GetParent(const node root,int val){       assert(NULL != root);       if (root->_value == val)       {              cout<<"found: "<<root->_value<<endl;              int* prt = new int(root->_value);              return prt;       }        stack<node> tree;       node n = root;       node tmp = NULL;        while ((!tree.empty()) || (NULL != root))       {              while (n != NULL)              {                     tree.push(n);                     n = n->_lchild;              }               if (!tree.empty())              {                     int len = tree.size();                     int* prt = new int[len];                     int i = 0;                      tmp = tree.top();                     if (tmp->_value == val)                     {                            while (tree.size() > 0)                            {                                   prt[i++] = tree.top()->_value;                                   cout<<tree.top()->_value<<"->";                                   tree.pop();                            }                            cout<<endl;                             return prt;                     }                     else                            n = n->_rchild;              }       }        return NULL;}