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

来源:互联网 发布:网速流量监控软件 编辑:程序博客网 时间:2024/06/09 19:42

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

struct BinaryTreeNode{int m_nValue;BinaryTreeNode *m_pLeft;BinaryTreeNode *m_pRight;};void FindPath (BinaryTreeNode *pTreeNode, int expectedSum, vector<int> &path, int &currentSum){if (pTreeNode == NULL)return;currentSum += pTreeNode->m_nValue;path.push_back(pTreeNode->m_nValue);bool isLeaf = (!pTreeNode->m_pLeft && !pTreeNode->m_pRight);if (currentSum == expectedSum && isLeaf){vector<int>::iterator iter = path.begin();for (; iter != path.end(); ++iter)cout << *iter << '\t';cout << endl;}if (pTreeNode->m_pLeft) FindPath(pTreeNode->m_pLeft, expectedSum, path, currentSum); if (pTreeNode->m_pRight) FindPath(pTreeNode->m_pRight, expectedSum, path, currentSum);currentSum -= pTreeNode->m_nValue;path.pop_back();}


原创粉丝点击