【练习】在二元树中找出和为某一值的所有路径
/************************************************************************/ /* 4.在二元树中找出和为某一值的所有路径 题目:输入一个整数和一棵二元树。 从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。 打印出和与输入整数相等的所有路径。 3 例如输入整数22 和如下二元树 10 / \ 5 12 / \ 4 7 则打印出两条路径:10, 12 和10, 5, 7。 二元树节点的数据结构定义为: struct BinaryTreeNode // a node in the binary tree { int m_nValue; // value of node BinaryTreeNode *m_pLeft; // left child of node BinaryTreeNode *m_pRight; // right child of node };算法思想:先序遍历二叉树,直到找到叶子结点,并判断此路径上的元素和是否符合条件,然后返回父结点继续下一条路径 */ /************************************************************************/ #include <iostream> #include <vector> using namespace std; struct BinaryTreeNode // a node in the binary tree { int m_nValue; // value of node BinaryTreeNode *m_pLeft; // left child of node BinaryTreeNode *m_pRight; // right child of node }; void addBTNode(BinaryTreeNode* &btn,int value); void findPath(BinaryTreeNode* btn,int sum); int currentSum=0; vector<int> path; int main() { BinaryTreeNode* btn=NULL; addBTNode(btn,10); addBTNode(btn,5); addBTNode(btn,12); addBTNode(btn,4); addBTNode(btn,7); findPath(btn,22); } void addBTNode(BinaryTreeNode* &btn,int value) { if (NULL==btn) { BinaryTreeNode *pBtn=new BinaryTreeNode(); pBtn->m_nValue=value; pBtn->m_pLeft=NULL; pBtn->m_pRight=NULL; btn=pBtn; } else { if (value>btn->m_nValue) { addBTNode(btn->m_pRight,value); } else if (value<btn->m_nValue) { addBTNode(btn->m_pLeft,value); } else { cout<<"node repeated"<<endl; } } } void findPath(BinaryTreeNode* btn,int sum) { if (btn) { path.push_back(btn->m_nValue); currentSum+=btn->m_nValue; bool isLeaf=(btn->m_pLeft==NULL)&&(btn->m_pRight==NULL); if (isLeaf&&sum==currentSum) { for (int i=0;i<path.size();i++) { cout<<path[i]<<" "; } cout<<endl; } if (btn->m_pLeft) { findPath(btn->m_pLeft,sum); } if (btn->m_pRight) { findPath(btn->m_pRight,sum); } currentSum-=btn->m_nValue; path.pop_back(); } }