拿不準(zhǔn)的遍歷順序,搞不清的回溯過(guò)程,我太難了! | LeetCode:112.

Leetcode 112.路徑總和:遞歸函數(shù)沒(méi)有返回值也是可以的(leetcode 8ms)
class?Solution?{
public:
????bool?hasPath?=?false; // 定義一個(gè)全局結(jié)果變量
????void?backtracking(TreeNode*?root,?int?pathSum,?int?targetSum)?{
????????if?(hasPath)?return; // 如果已經(jīng)找到 不在繼續(xù)遞歸遍歷
????????if?(!root->left?&&?!root->right)?{
????????????if?(pathSum?==?targetSum)?hasPath?=?true;
????????????return;
????????}
????????if?(root->left)?{
????????????pathSum?+=?root->left->val;
????????????backtracking(root->left,?pathSum,?targetSum);
????????????pathSum?-=?root->left->val;
????????}
????????if?(root->right)?{
????????????pathSum?+=?root->right->val;
????????????backtracking(root->right,?pathSum,?targetSum);
????????????pathSum?-=?root->right->val;
????????}
????}
????bool?hasPathSum(TreeNode*?root,?int?targetSum)?{
????????if?(!root)?return?false;
????????backtracking(root,?root->val,?targetSum);
????????return?hasPath; // 返回結(jié)果
????}
};