题目:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从根结点开始往下一直到叶结点所经过的结点形成一条路径。
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
解法:
void findPath(BinaryTreeNode* pRoot, int expectSum) {
if (pRoot == 0) return;
std::vector<int> path;
int currentSum = 0;
findPathRecursive(pRoot, expectSum, path, currentSum);
}
void findPathRecursive(BinaryTreeNode* pRoot, int expectSum, std::vector<int> path, int currentSum) {
if (pRoot == 0) return;
path.push_back(pRoot->m_nValue);
currentSum += pRoot->m_nValue;
bool isLeaf = pRoot->m_pLeft == 0 && pRoot->m_pRight == 0;
if (expectSum == currentSum && isLeaf) {
// find path
print(path);
}
if (pRoot->m_pLeft != 0) {
findPathRecursive(pRoot->m_pLeft, expectSum, path, currentSum);
}
if (pRoot->m_pRight != 0) {
findPathRecursive(pRoot->m_pRight, expectSum, path, currentSum);
}
//返回父节点之前,在路径上删除当前结点
currentSum -= pRoot->m_nValue;
path.pop_back();
}