輸入二叉樹根節點與整數 target,打印所有從根到葉子節點路徑上節點值之和等於 target 的路徑。
struct BinaryTreeNode {
int val;
BinaryTreeNode *left, *right;
};
vector path;
void FindPath(BinaryTreeNode* root, int target, int curSum) {
if (!root) return;
curSum += root->val;
path.push_back(root);
if (curSum == target && !root->left && !root->right) {
for (auto node : path) printf("%d ", node->val);
printf("\n");
}
FindPath(root->left, target, curSum);
FindPath(root->right, target, curSum);
path.pop_back(); // 回溯關鍵
}