在二元树中找出和为某一值的所有路径

来源:互联网 发布:淘宝贷款出额度付3000 编辑:程序博客网 时间:2024/05/21 11:07

输入一个整数和一棵二元树,从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径,然后打印出和与输入整数相等的所有路径。

#include <iostream>#include<stack>#include<vector>using namespace std;typedef struct BinaryTreeNode {int m_nValue;BinaryTreeNode * m_pLeft;BinaryTreeNode * m_pRight;} BinaryTreeNode; /* 表示一个元素的三元组结构 */vector<int> vec;void initTree(BinaryTreeNode* head);void findRoute(BinaryTreeNode* head, int arg0, int count);int main() {BinaryTreeNode* head = new BinaryTreeNode();initTree(head);int arg0 = 22;int count = 0;cout << "二叉树中和为" << arg0 << "的路径:" << endl;findRoute(head, arg0, count);return 0;}void initTree(BinaryTreeNode* head) {if (!head)return;BinaryTreeNode* child1 = new BinaryTreeNode();BinaryTreeNode* child2 = new BinaryTreeNode();BinaryTreeNode* child3 = new BinaryTreeNode();BinaryTreeNode* child4 = new BinaryTreeNode();head->m_nValue = 10;child1->m_nValue = 5;child2->m_nValue = 12;child3->m_nValue = 4;child4->m_nValue = 7;head->m_pLeft = child1;head->m_pRight = child2;child1->m_pLeft = child3;child1->m_pRight = child4;}void findRoute(BinaryTreeNode* head, int arg0, int count) {if (!head) {return;} else {if (count + head->m_nValue == arg0) {if (head->m_pLeft || head->m_pRight) {//非叶子结点return;} else {for (int i = 0; i < vec.size(); ++i) {cout << " " << vec[i];}cout << " " << head->m_nValue << endl;return;}} else if (count + head->m_nValue > arg0) {return;} else {if (head->m_pLeft) {vec.push_back(head->m_nValue);findRoute(head->m_pLeft, arg0, count + head->m_nValue);vec.erase(vec.end() - 1);}if (head->m_pRight) {vec.push_back(head->m_nValue);findRoute(head->m_pRight, arg0, count + head->m_nValue);vec.erase(vec.end() - 1);}}}}


1 0
原创粉丝点击