Output all the paths from the root node to the leaf node in the binary tree.

Source: Internet
Author: User

// Output all the paths from the root node to the leaf node in the binary tree. cpp: defines the entry point of the console application. # Include "stdafx. h "# include <iostream >#include <vector> using namespace std; struct BTNode {char m_value; BTNode * m_left; BTNode * m_right ;}; // create a binary tree void CreatBTree (BTNode * & root) {char nValue = 0; cin> nValue; if ('#' = nValue) {return ;} else {root = new BTNode (); root-> m_value = nValue; CreatBTree (root-> m_left); CreatBTree (root-> m_right );}} // output all paths from the root node to the leaf node in the binary tree (recursion) void FindAllPath (BTNode * pRoot, vector <cha R> path) {if (pRoot! = NULL) {path. push_back (pRoot-> m_value); if (pRoot-> m_left = NULL & pRoot-> m_right = NULL) {for (vector <char> :: iterator iter = path. begin (); iter! = Path. end (); iter ++) {cout <* iter <";}cout <endl; return ;}else {FindAllPath (pRoot-> m_left, path ); findAllPath (pRoot-> m_right, path) ;}} int _ tmain (int argc, _ TCHAR * argv []) {BTNode * pRoot = NULL; vector <char> path; creatBTree (pRoot); cout <"all the paths from the root tree to the leaf node are as follows:" <endl; FindAllPath (pRoot, path); system ("pause "); return 0 ;}

Running result:


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.