输入一棵二叉树和一个整数,打印出二叉树中节点值和输入整数的所有路径
定和子集问题,剪枝
void FindPath(BinaryTreeNode *pRoot, int expectedSum) { if(pRoot == nullptr) return; vector<int>path; int currentSum = 0; FindPath(pRoot, expectedSum, path, currentSum); } void FindPath(BinaryTreeNode *pRoot, int expectedSum, vector<int>path, int cuurentSum) { currentSum += pRoot->val; path.push_back(pRoot->val); bool isLeaf = pRoot->left == nullptr && pRoot->right == nullptr; if(currentSum == expectedSum && isLeaf) { printf("A path is found:"); vector<int>::iterator iter = path.begin(); for(;iter !=path.end();++iter) printf("%d\t", *iter); print("\n"); } if(pRoot->left != nullptr) FindPath(pRoot->left, expectedSum, path, currentSum); if(pRoot->right !=nullptr) FindPath(pRoot->right, expectedSum, path, currentSum); path.pop_back(); }