112. Path Sum (Tree; DFS)
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool hasPathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function if(!root) return false; flag = false; target = sum; preOrder(root,0); return flag; } void preOrder(TreeNode* node,int sum){ sum = node->val + sum; //递归前,加上当前节点 if(node->left) { preOrder(node->left,sum); } if(node->right) { preOrder(node->right,sum); } if(!node->left && !node->right && sum == target) //递归结束条件:到了叶子节点 { flag = true; } } private: bool flag; int target; };