Depth of Tree nodes in Binary Trees

Source: Internet
Author: User
/** 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.