题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param sum int整型 * @return bool布尔型 */ bool hasPathSum(TreeNode* root, int sum) { // write code here // 空集返回false if (!root) return false; return preOrd(root, sum); } // 前序遍历方式查询 bool preOrd(TreeNode* root, int sum) { if (!root) return false; // 找到最后都没有凑够,返回查询失败 sum -= root->val; if(!root->left && !root->right && sum == 0) return true; // 找到节点的子节点均为空,并且sum值刚好为0,则找到了 if(preOrd(root->left, sum) || preOrd(root->right, sum)) return true; return false; // 找了一圈没找到,则认为查询失败 } };
挤挤刷刷! 文章被收录于专栏
记录coding过程