/** Proot receives the root node of the tree to be retrieved. pnode is the Node path to be confirmed to store all nodes from the root node to the pnode, including pnode and root node */void findpath (binarytreenode * proot, binarytreenode * pnode, vector <int> & Path) {If (proot = NULL) return; Path. push_back (proot-> m_nvalue); If (proot = pnode) {// If the node is found, printf ("A path is found: \ n"); return ;} vector <int>: size_type presize = path. size (); // If pnode is found in the left subtree, do not release the current node. findpath (proot-> m_pleft, pnode, PATH) is returned immediately ); // cleverly use the size increase of path to determine whether to find the node if (presize <path. size () return; // If pnode is found in the left subtree, do not release the current node. findpath (proot-> m_pright, pnode, PATH) is returned immediately ); // If pnode is found in the left subtree, do not release the current node. If (presize <path. size () return; Path. pop_back ();}
The most common problem is that the node is not discussed separately when the subtree finds the node, which leads to the execution of path. pop_back (), releasing the currently pressed container node, resulting in a logical error.
At last, you just need to print the path. Size ()-1, which is the depth of the node.
It can be seen that recursive writing can show tracing ideas in simple and elegant ways, and mastering recursive writing is a manifestation of programmer's ability.